如何提升嵌套两层深度的JSON对象的值



给定我从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中。我已经搜索并找到了一种使用jq访问嵌套对象的方法。但是,我如何访问嵌套在主list对象中另一个对象内的值呢?

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

提前感谢!

以下内容可以很容易地扩展和/或调整:

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

输出:

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

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

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

第一个滤波器仅对list元件进行操作。第二个滤波器说for every element,最后输出的只是resolved_title.word_count字段。这会产生以下内容:

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

尝试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"
  }
]

相关内容

  • 没有找到相关文章

最新更新