0

我有一个返回 JSON 的 API - 它的大块。一些键值对具有更多的 JSON 块作为与键关联的值。jq 在解析主要 JSON 级别方面做得很好。但我找不到一种方法让它“递归”到与键关联的值并漂亮地打印它们。

这是其中一个 JSON 返回的开始。请注意,这只是全部回报的一小部分:

    {
  "code": 200,
  "status": "OK",
  "data": {
    "PlayFabId": "xxxxxxx",
    "InfoResultPayload": {
      "AccountInfo": {
        "PlayFabId": "xxxxxxxx",
        "Created": "2018-03-22T19:23:29.018Z",
        "TitleInfo": {
          "Origination": "IOS",
          "Created": "2018-03-22T19:23:29.033Z",
          "LastLogin": "2018-03-22T19:23:29.033Z",
          "FirstLogin": "2018-03-22T19:23:29.033Z",
          "isBanned": false
        },
        "PrivateInfo": {},
        "IosDeviceInfo": {
          "IosDeviceId": "xxxxxxxxx"
        }
      },
      "UserVirtualCurrency": {
        "GT": 10,
        "MB": 70
      },
      "UserVirtualCurrencyRechargeTimes": {},
      "UserData": {},
      "UserDataVersion": 15,
      "UserReadOnlyData": {
        "DataVersion": {
          "Value": "6",
          "LastUpdated": "2018-03-22T19:48:59.543Z",
          "Permission": "Public"
        },
        "achievements": {
          "Value": "[{\"id\":0,\"gamePack\":\"GAME.PACK.0.KK\",\"marblesAmount\":50,\"achievements\":[{\"id\":2,\"name\":\"Correct Round 4\",\"description\":\"Round 4 answered correctly\",\"maxValue\":10,\"increment\":1,\"currentValue\":3,\"valueUnit\":\"unit\",\"awardOnIncrement\":true,\"marbles\":10,\"image\":\"https://www.jamandcandy.com/kissinkuzzins/achievements/icons/sphinx\",\"SuccessKey\":[\"0_3_4_0\",\"0_5_4_0\",\"0_6_4_0\",\"0_7_4_0\",\"0_8_4_0\",\"0_9_4_0\",\"0_10_4_0\"],\"event\":\"Player_answered_round\",\"achieved\":false},{\"id\":0,\"name\":\"Complete

这是使用 jq 解析的,但是当您到达

"achievements": { "Vales": "[{\"id\":0,\"gamePack\":\"GAME.PACK.0.KK\",\"marblesAmount\":50,\

lq 没有进一步解析值也是 JSON。

我是否缺少一个过滤器来解析值以及更高级别的结构?

4

1 回答 1

0

有没有我缺少的过滤器......?

您需要的过滤器是fromjson,但它应该只应用于字符串化的 JSON;因此考虑|=使用您的片段,如图所示:

echo '{"achievements": { "Vales": "[{\"id\":0,\"gamePack\":\"GAME.PACK.0.KK\",\"marblesAmount\":50}]"}}' | 
  jq '.achievements.Vales |= fromjson'

{
  "achievements": {
    "Vales": [
      {
        "id": 0,
        "gamePack": "GAME.PACK.0.KK",
        "marblesAmount": 50
      }
    ]
  }
}

递归/1

如果您想fromjson尽可能递归地应用,那么recursively您的朋友是:

def recursively(f):
  . as $in
  | if type == "object" then
      reduce keys[] as $key
        ( {}; . + { ($key):  ($in[$key]  | recursively(f) )} )
  elif type == "array" then map( recursively(f) )
  else try (f as $f | if $f == . then . else ($f | recursively(f)) end) catch $in
  end;

这将应用如下:

recursively(fromjson)

例子

{a: ({b: "xyzzy"}) | tojson} | tojson 
| recursively(fromjson)

产量:

{
  "a": {
    "b": "xyzzy"
  }
}
于 2018-03-22T20:59:26.523 回答