【问题标题】:Add new list, string and restructure to existing JSON array with jq使用 jq 向现有 JSON 数组添加新列表、字符串和重组
【发布时间】:2021-01-25 00:55:30
【问题描述】:

我有这个 input.json

{
   "list": [
      {
         "something1": "aaaa",
         "status": {
            "totalItems": 2,
            "Items": [
               {
                  "city": "santa",
                  "state": "VA",
                  "adress": "1 avenue"
               },
               {
                  "city": "manhatan",
                  "state": "NY",
                  "adress": "1 drive"
               }
            ]
         }
      },
      {
         "something1": "bbbb",
         "status": {
            "totalItems": 0
         }
      }
   ]
}

我想添加列表并在值之间附加一些文本并输出如下:

{
   "Newlist": [
      {
         "name": "NewName.aaaa",
         "HaveItem": "Yes",
         "Data": [
            "santa is a city of VA with address 1 avenue",
            "manhatan is a city of NY with address 1 drive"
         ]
      },
      {
         "name": "NewName.bbbb",
         "HaveItem": "No"
      }
   ]
}

我尝试过使用 jq '.list | map({name: .something1, HaveItem: (if .status.totalItems != 0 then "Yes" else "No" end), Data: (if .status.totalItems != 0 then .status.Items else "NULL" end) })' 但我不知道如何在值之间添加字符串。

【问题讨论】:

    标签: json string concatenation jq


    【解决方案1】:

    连接两个字符串的一种方法是使用+,例如而不是

    name: .something1
    

    你会写

    name: ("NewName." + .something1)
    

    以您的查询为起点,下一步是将所有内容包装在一个以Newlist 为键的对象中:

    { Newlist:
        .list
        | map({name: ("NewName." + .something1),
               HaveItem:
                 (if .status.totalItems != 0 
                  then "Yes" 
                  else "No" end),
               Data: 
                 (if .status.totalItems != 0
                  then .status.Items
                  else "NULL" end)
        } ) }
    

    您应该能够对其进行调整以产生您想要的最终结果。

    【讨论】:

    • 如何用jq将地图转成list?
    猜你喜欢
    • 2017-07-03
    • 1970-01-01
    • 2021-10-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多