将Shopify JSONL文件转换为JSON

时间:2019-12-20 17:12:39

标签: json jq json-ld

我有一个Shopify jsonl文件,我正在尝试将其映射到其他json结构。

输入以下内容:

{"id":"gid:\/\/shopify\/Product\/123456789","title":"Gift Card"}
{"originalSrc":"https:\/\/cdn.shopify.com\/s\/files\/1\/1111\/2222\/products\/gift-card-01.jpg","__parentId":"gid:\/\/shopify\/Product\/123456789"}
{"originalSrc":"https:\/\/cdn.shopify.com\/s\/files\/1\/1111\/2222\/products\/gift-card-02.jpg","__parentId":"gid:\/\/shopify\/Product\/123456789"}

我想使用__parentId将图像映射到正确的产品ID。

[
  {
    "id":"gid:\/\/shopify\/Product\/123456789",
    "title":"Gift Card",
    "images: [
      "https:\/\/cdn.shopify.com\/s\/files\/1\/1111\/2222\/products\/gift-card-01.jpg",
      "https:\/\/cdn.shopify.com\/s\/files\/1\/1111\/2222\/products\/gift-card-02.jpg"
    ]
  },
  ...
]

1 个答案:

答案 0 :(得分:1)

以下解决方案首先用ID增量构造字典和对象数组, 然后使用map产生所需的结果:

reduce inputs as $x ({};
  if $x|has("id") then .objects += [$x]
  elif $x|has("__parentId") then .dict[$x.__parentId] += [$x.originalSrc]
  else . # an error?
  end)
| .dict as $dict
| .objects
| map( . + {images: $dict[.id]})

调用

必须使用-n命令行选项,例如

jq -nf shopify.jq shopify.json