如何解析同一json文件中数组内部的数组?

时间:2019-07-15 08:04:19

标签: json jq

如何解析同一JSON文件中的数组中的数组?

这是JSON文件:

{
  "customers": [
    {
      "id": 268467952,
      "firstName": "And",
      "lastName": "Little",
      "gender": "Unknown",
      "photoType": "default",
      "photoUrl": "https://d33v4339jhl8k0.cloudfront.net/customer-avatar/02.png",
      "createdAt": "2019-07-10T12:37:42Z",
      "updatedAt": "2019-07-10T12:37:41Z",
      "background": "",
      "_embedded": {
        "emails": [
          {
            "id": 360891952,
            "value": "info@look.co.uk",
            "type": "work"
          }
        ]}
}]}

我想要这样的输出:

{
  "id": 268467952,
  "id": 360891952,
  "value": "info@thatweblook.co.uk",
  "type": "work"
}

我尝试运行此命令,但在emails.id,emails.value,emails.type列中为空:

jq '

{customers: .customers[], _embedded: ._embedded }
| if ._embedded == null then

{id: .customers .id, idemail: null, valueemail: null, typeemail: null}
else

{id: .customers .id, id: ._embedded .emails[] .id, value: ._embedded .emails[] .value,  type: ._embedded .emails[] .type }
end'  /home/help-scout/only-cust/file.json > //home/help-scout/only-cust-read/file-cust-read.json

从此代码中,我在email列中为空:

{
  "id": 268467952,
  "idemail": null,
  "valueemail": null,
  "typeemail": null
}

请协助:) 谢谢!

1 个答案:

答案 0 :(得分:0)

尽管问题中所示的预期输出在技术上是有效的JSON,但出于各种原因,不建议重复键。因此,至少现在假设以下输出是可接受的:

{
  "customerid": 268467952,
  "id": 360891952,
  "value": "info@look.co.uk",
  "type": "work"
}

这可以通过jq过滤器生成:

.customers[] | {customerid: .id} + ._embedded.emails[]

现在,如果您真的希望对键进行不明智的重复,则可以通过sed或awk等文本处理工具运行jq产生的输出。

相关问题