使用命令行探索 json

问题描述 投票:0回答:1

有人可以帮我用命令行找到这个问题的解决方案吗? 这是我的 Json 文件:

{
  "type": "record",
  "name": "ShelfEx »position,
  "fields": [
    {
      "name": "shopId",
      "type": {
        "type": "string",
        "avro.java.string": "String"
      },
      "doc": "Id of the shop"
    },
    {
      "name": "productId",
      "type": {
        "type": "string",
        "avro.java.string": "String"
      },
      "doc": "Id of the product"
    },
    {
      "name": "sourceId",
      "type": {
        "type": "string",
        "avro.java.string": "String"
      },
      "doc": "Id of the source"
    },
    {
      "name": "timestampTransmission",
      "type": "long",
      "doc": "Timestamp of the message"
    },
    {
      "name": "productQuantity",
      "type": [
        "null",
        "double"
      ],
      "doc": "Quantity of the product",
      "default": null
    }
  ]
}

我想获取每个字段的名称、类型以及最终的默认值(在 ProductQuantity 的情况下为 null)。 所以输出应该是这样的:

"shopId" string
"productId" string
...
"timestampTransmission" long
"productQuantity" double null

请问有什么想法吗?

`cat file.json | jq -r '.fields[] | "\"\(.name)\" : \(.type | tostring | sub("^(null)$"; "\\1 :     null") | sub("(^\"|\"$)"; ""))"'`

而不是:

"shopId" string
"productId" string
...
"timestampTransmission" long
"productQuantity" double null

我有:

"shopId" : {"type":"string","avro.java.string":"String"}
"productId" : {"type":"string","avro.java.string":"String"}
"sourceId" : {"type":"string","avro.java.string":"String"}
"timestampTransmission" : long
"productQuantity" : ["null","double"]
linux shell command-line jq
1个回答
0
投票

如果我正确理解你的格式,你想要

.fields[] | [

  # .name in quotes (what about escaping?)
  "\"\(.name)\"",

  # .type.type or .type[] or .type as a scalar, filtering out null
  (.type | objects.type // arrays[] // . | select(. != "null")),

  # .default, only if it exists
  (select(has("default")).default | tostring)

] | join(" ")

将其用作

jq -r '…' file.json
来获取

"shopId" string
"productId" string
"sourceId" string
"timestampTransmission" long
"productQuantity" double null

演示

© www.soinside.com 2019 - 2024. All rights reserved.