如何解除嵌套两层深度的JSON对象的值?

时间:2016-03-26 12:59:32

标签: json command-line jq pocket

鉴于我作为Pocket API的回复收到了以下test.json

{
"complete": 1,
"error": null,
"list": {
    "1000055792": {
        "excerpt": "Some Text",
        "favorite": "0",
        "given_title": "Some Title",
        "given_url": "Some URL",
        "has_image": "0",
        "has_video": "0",
        "is_article": "1",
        "is_index": "0",
        "item_id": "1000055792",
        "resolved_id": "1000055792",
        "resolved_title": "Title",
        "resolved_url": "Some URL",
        "sort_id": 700,
        "status": "1",
        "time_added": "1438646514",
        "time_favorited": "0",
        "time_read": "1439025088",
        "time_updated": "1439025090",
        "word_count": "10549"
    },
    "1000102810": {
        "excerpt": "Some Text",
        "favorite": "0",
        "given_title": "Title",
        "given_url": "Some URL",
        "has_image": "1",
        "has_video": "0",
        "is_article": "1",
        "is_index": "0",
        "item_id": "1000102810",
        "resolved_id": "1000102810",
        "resolved_title": "Title",
        "resolved_url": "Resolved URL",
        "sort_id": 650,
        "status": "1",
        "time_added": "1440303789",
        "time_favorited": "0",
        "time_read": "1440320729",
        "time_updated": "1440320731",
        "word_count": "3219"
    }

如何访问resolved_titleword_count等密钥的值。它们嵌套在一个对象中,该对象是一个数字,与id相同,list本身嵌套在list内。我搜索并找到了一种使用jq访问嵌套对象的方法。但是,如何访问嵌套在主resolved_title对象中的另一个对象内的值?

此外,ID是不同的而不是顺序的,所以我不认为递归是可能的,但我可能是错的。我打算对这些数据做的只是提取每个项目的word_countof值,并将它们保存到两列电子表格中。

提前致谢!

3 个答案:

答案 0 :(得分:1)

以下内容可以轻松扩展和/或改编:

> jq ".list[] | {resolved_title, word_count}" input.json

输出:

{
  "resolved_title": "Title",
  "word_count": "10549"
}
{
  "resolved_title": "Title",
  "word_count": "3219"
}

答案 1 :(得分:0)

您可以使用.[]运算符迭代数组中的所有元素(或者在本例中为所有键)。以下内容将为您提供单独行中每个字段的输出:

cat <file_with_json> | jq '.list | .[] | .resolved_title, .word_count'

第一个过滤器仅对list元素进行操作。第二个过滤器显示for every element,最后输出只是resolved_title.word_count字段。这产生以下结果:

"Title"
"3219"
"Title"
"10549"

答案 2 :(得分:0)

尝试map()

$ cat myfile.json | jq '.list | map({resolved_title: .resolved_title, word_count: .word_count})'
[
  {
    "resolved_title": "Title",
    "word_count": "10549"
  },
  {
    "resolved_title": "Title",
    "word_count": "3219"
  }
]