使用JQ进行JSON转换

时间:2019-02-12 03:03:27

标签: json iteration transform jq

我正在尝试使用JQ将JSON转换为其他结构。我可以部分实现我的新结构,但是我获得了额外的数据块。

当我迭代时,我能够以新格式获取结构。但是还会有其他结构。

代码段-https://jqplay.org/s/3gulSlZiWz

JSON

    {
      "amazon": {
        "activeitem": 2,
        "createdDate": "2019-01-15T17:36:31.588Z",
        "lastModifiedDate": "2019-01-15T17:36:31.588Z",
        "user": "net",
        "userType": "new",
        "items": [
          {
            "id": 1,
            "name": "harry potter",
            "state": "sold",
            "type": {
              "branded": false,
              "description": "artwork",
              "contentLevel": "season"
            }
          },
          {
            "id": 2,
            "name": "adidas shoes",
            "state": "in inventory",
            "type": {
              "branded": false,
              "description": "Spprts",
              "contentLevel": "season"
            }
          },
          {
            "id": 3,
            "name": "watch",
            "state": "returned",
            "type": {
              "branded": false,
              "description": "walking",
              "contentLevel": "special"
            }
          },
          {
            "id": 4,
            "name": "adidas shoes",
            "state": "in inventory",
            "type": {
              "branded": false,
              "description": "running",
              "contentLevel": "winter"
            }
          }
        ],
        "product": {
          "id": 4,
          "name": "adidas shoes",
          "source": "dealer",
          "destination": "resident"
        }
      }
    }

JQ查询:

      .amazon| 
      {  
          userType: .userType,
          userName: .user,
          itemCatalog: {   
             itemId: .items[].id, 
             name: .items[].name  
          }
      }

预期的响应:

 {
    "userType": "new",
    "userName": "net",
    "itemCatalog": {
      "itemId": 1,
      "name": "harry potter"
    },{
      "itemId": 2,
      "name": "adidas shoes"
    }, {
      "itemId": 3,
      "name": "watch"
    },{
      "itemId": 4,
      "name": "adidas shoes"
    }
  }

但是得到一些奇怪的长期重复的答复。

1 个答案:

答案 0 :(得分:1)

正如评论中已经指出的那样,“期望的响应”不是JSON,可能也不是您想要的。以下内容将很有意义,并且无论如何都说明了如何适当地进行迭代:

select  oneerror.date_column, round(((cast(oneerror.request_error as decimal))/requests*1.0),2) as percent
from (select date(log.time) AS date_column,
        count (*) as request_error
        from log where not status = '200 OK'
    group by date_column) as oneerror
join (select date(log.time) AS date_column,
        count(*) as requests
    from log
    group by date_column) as total
on oneerror.date_column = total.date_column
    where round((cast(oneerror.request_error as decimal)/requests*1.0),3)> 0.01
order by percent desc
          ''')
number_one_error = c.fetchall()
db.close()

输出

.amazon
| { userType: .userType,
    userName: .user,
    itemCatalog: (.items | map({ itemId: .id, name} ))
  }