255 lines
6.0 KiB
Go
255 lines
6.0 KiB
Go
package feeds
|
|
|
|
import (
|
|
"bufio"
|
|
"bytes"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"regexp"
|
|
"sort"
|
|
"strconv"
|
|
"strings"
|
|
)
|
|
|
|
// parseJSONItems consumes one object at a time from a root array or a nested array
|
|
// (data.products, results, items, SHOPITEM, etc). It does not buffer the catalog.
|
|
func parseJSONItems(r io.Reader, itemPath string, onRow func(feedRow) error) (int, error) {
|
|
dec := json.NewDecoder(bufio.NewReader(r))
|
|
dec.UseNumber()
|
|
first, err := dec.Token()
|
|
if err != nil {
|
|
return 0, fmt.Errorf("json: %w", err)
|
|
}
|
|
count := 0
|
|
var visit func(any, []string) error
|
|
visit = func(token any, path []string) error {
|
|
delim, ok := token.(json.Delim)
|
|
if !ok {
|
|
return nil
|
|
}
|
|
switch delim {
|
|
case '[':
|
|
if jsonItemPathMatches(itemPath, path) || (itemPath == "" && isLikelyJSONItemArray(path)) {
|
|
for dec.More() {
|
|
var raw json.RawMessage
|
|
if err := dec.Decode(&raw); err != nil {
|
|
return err
|
|
}
|
|
var obj any
|
|
d := json.NewDecoder(bytes.NewReader(raw))
|
|
d.UseNumber()
|
|
if err := d.Decode(&obj); err != nil {
|
|
return err
|
|
}
|
|
if _, ok := obj.(map[string]any); !ok {
|
|
continue
|
|
}
|
|
row := feedRow{}
|
|
flattenJSONValue(row, "", obj, 0)
|
|
expandSpecificationFields(row)
|
|
count++
|
|
if count > maxParseRows {
|
|
return parseTooManyRows()
|
|
}
|
|
if err := onRow(row); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
} else {
|
|
for dec.More() {
|
|
next, e := dec.Token()
|
|
if e != nil {
|
|
return e
|
|
}
|
|
if err := visit(next, path); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
}
|
|
case '{':
|
|
for dec.More() {
|
|
k, e := dec.Token()
|
|
if e != nil {
|
|
return e
|
|
}
|
|
key, _ := k.(string)
|
|
next, e := dec.Token()
|
|
if e != nil {
|
|
return e
|
|
}
|
|
if err := visit(next, append(append([]string(nil), path...), key)); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
default:
|
|
return fmt.Errorf("invalid JSON document")
|
|
}
|
|
_, err := dec.Token()
|
|
return err
|
|
}
|
|
if err := visit(first, nil); err != nil {
|
|
return count, fmt.Errorf("json: %w", err)
|
|
}
|
|
if count == 0 {
|
|
return 0, errors.New("JSON contained no product records; check item path (for example products or data/products)")
|
|
}
|
|
return count, nil
|
|
}
|
|
|
|
func jsonItemPathMatches(hint string, path []string) bool {
|
|
hint = strings.Trim(strings.ToLower(strings.TrimSpace(hint)), "/.")
|
|
if hint == "" {
|
|
return false
|
|
}
|
|
hint = strings.ReplaceAll(hint, ".", "/")
|
|
actual := strings.ToLower(strings.Join(path, "/"))
|
|
return actual == hint || strings.HasSuffix(actual, "/"+hint)
|
|
}
|
|
func isLikelyJSONItemArray(path []string) bool {
|
|
if len(path) == 0 {
|
|
return true
|
|
}
|
|
name := strings.ToLower(path[len(path)-1])
|
|
switch name {
|
|
case "products", "product", "items", "shopitem", "results", "entries", "offers", "rows", "records", "data":
|
|
return true
|
|
}
|
|
return false
|
|
}
|
|
|
|
func flattenJSONValue(row feedRow, prefix string, v any, depth int) {
|
|
if depth > 12 || len(row) > 4000 {
|
|
return
|
|
}
|
|
switch x := v.(type) {
|
|
case map[string]any:
|
|
keys := make([]string, 0, len(x))
|
|
for k := range x {
|
|
keys = append(keys, k)
|
|
}
|
|
sort.Strings(keys)
|
|
for _, k := range keys {
|
|
path := k
|
|
if prefix != "" {
|
|
path = prefix + "/" + k
|
|
}
|
|
flattenJSONValue(row, path, x[k], depth+1)
|
|
}
|
|
case []any:
|
|
if len(x) == 0 {
|
|
return
|
|
}
|
|
// Attribute arrays [{name: ..., value: ...}] become named specification children.
|
|
for i, v := range x {
|
|
if i >= 250 {
|
|
return
|
|
}
|
|
if m, ok := v.(map[string]any); ok {
|
|
name := jsonString(m["name"])
|
|
if name == "" {
|
|
name = jsonString(m["PARAM_NAME"])
|
|
}
|
|
value := jsonString(m["value"])
|
|
if value == "" {
|
|
value = jsonString(m["VAL"])
|
|
}
|
|
if name != "" && value != "" {
|
|
row[prefix] = "Nested attributes"
|
|
row[prefix+"/"+sanitizePathSegment(name)] = value
|
|
continue
|
|
}
|
|
}
|
|
if s := jsonString(v); s != "" {
|
|
if _, ok := v.(map[string]any); !ok {
|
|
row[prefix+"/"+strconv.Itoa(i)] = s
|
|
continue
|
|
}
|
|
}
|
|
flattenJSONValue(row, prefix+"/"+strconv.Itoa(i), v, depth+1)
|
|
}
|
|
// For image galleries, keep the first URL in the parent path.
|
|
if _, ok := row[prefix]; !ok {
|
|
if first := jsonString(x[0]); first != "" {
|
|
row[prefix] = first
|
|
}
|
|
}
|
|
case nil:
|
|
return
|
|
default:
|
|
value := jsonString(v)
|
|
if value == "" {
|
|
return
|
|
}
|
|
row[prefix] = value
|
|
leaf := leafName(prefix)
|
|
if _, ok := row[leaf]; !ok && leaf != "" {
|
|
row[leaf] = value
|
|
}
|
|
}
|
|
}
|
|
func jsonString(v any) string {
|
|
switch x := v.(type) {
|
|
case string:
|
|
return x
|
|
case json.Number:
|
|
return string(x)
|
|
case bool:
|
|
return strconv.FormatBool(x)
|
|
case float64:
|
|
return strconv.FormatFloat(x, 'f', -1, 64)
|
|
}
|
|
return ""
|
|
}
|
|
|
|
// guessJSONItemPath picks a recognized list field in the preview; callers can override.
|
|
func guessJSONItemPath(data []byte) string {
|
|
var node any
|
|
dec := json.NewDecoder(bytes.NewReader(data))
|
|
dec.UseNumber()
|
|
if dec.Decode(&node) != nil {
|
|
// Schema previews intentionally stop at 512 KiB, often halfway through
|
|
// large JSON documents. Recognize the first array property in the prefix.
|
|
re := regexp.MustCompile(`(?i)"([^"\\]+)"\s*:\s*\[\s*\{`)
|
|
if parts := re.FindSubmatch(data); len(parts) > 1 {
|
|
return string(parts[1])
|
|
}
|
|
return ""
|
|
}
|
|
var find func(any, []string, int) string
|
|
find = func(v any, path []string, depth int) string {
|
|
if depth > 5 {
|
|
return ""
|
|
}
|
|
switch x := v.(type) {
|
|
case []any:
|
|
if len(x) > 0 {
|
|
if _, ok := x[0].(map[string]any); ok {
|
|
return strings.Join(path, "/")
|
|
}
|
|
}
|
|
case map[string]any:
|
|
for _, key := range []string{"products", "items", "SHOPITEM", "results", "data", "records", "product", "entries", "offers", "rows"} {
|
|
if n, ok := x[key]; ok {
|
|
if p := find(n, append(path, key), depth+1); p != "" || len(path) == 0 && key == "products" {
|
|
return p
|
|
}
|
|
}
|
|
}
|
|
keys := make([]string, 0, len(x))
|
|
for k := range x {
|
|
keys = append(keys, k)
|
|
}
|
|
sort.Strings(keys)
|
|
for _, k := range keys {
|
|
if p := find(x[k], append(path, k), depth+1); p != "" {
|
|
return p
|
|
}
|
|
}
|
|
}
|
|
return ""
|
|
}
|
|
return find(node, nil, 0)
|
|
}
|