簡體   English   中英

如何從 JSON 中讀取嵌套數組元素?

[英]How to read nested array elements from JSON?

我需要用嵌套數組元素解析 JSON 並提取值。

我不確定如何使用嵌套數組來設置 output JSON 中的屬性值。

這是輸入:

  [{
        "name": "book1",
        "id": 18789,
        "locations": [{
            "state": "mystate",
            "phone": 8877887700
        }, {
            "state": "mystate1",
            "phone": 8877887701
        }]
    },
    {
        "name": "book2",
        "id": 18781,
        "locations": [{
            "state": "mystate3",
            "phone": 8877887711
        }, {
            "state": "mystate4",
            "phone": 8877887702
        }]
    }]

這是預期的 output:

{
    "name": ["book1", "book2"],
    "id": ["18789", "18781"],
    "states": [
        ["mystate", "mystate"],
        ["mystate3", "mystate4"]
    ]
}

我正在嘗試使用以下 JSLT 表達式:

{
  "name" : [for (.)
               let s = string(.name)
               $s],
"id": [for (.)
               let s = string(.id)
               $s],
"states": [for (.)
               let s = string(.locations)
               $s]
}  

但我不確定在這種情況下如何設置states ,以便在 output 中獲得 state 的值。

使用 JQ 或 JSONPath 的解決方案也可能有所幫助。

使用 JQ 會比這更容易。

{
  name:   map(.name),
  id:     map(.id),
  states: map(.locations | map(.state))
}

在線演示

在 JSLT 中你可以這樣實現它:

{
  "name" : [for (.) .name],
  "id": [for (.) .id],
  "states": flatten([for (.) [for (.locations) .state]])
} 

如您所見, states鍵的實現有點尷尬。 我曾想過讓路徑表達式遍歷 arrays 成為可能,如果我們將其添加到語言中,它可以像這樣實現:

{
  "name" : .[].name,
  "id": .[].id,
  "states": .[].locations.[].state
} 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM