1

鉴于test.json我从 Pocket API 收到的以下响应,

{
"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值并将它们保存到一个两列的电子表格中。

提前致谢!

4

3 回答 3

1

以下内容可以轻松扩展和/或调整:

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

输出:

{
  "resolved_title": "Title",
  "word_count": "10549"
}
{
  "resolved_title": "Title",
  "word_count": "3219"
}
于 2016-04-01T04:34:17.167 回答
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"
  }
]
于 2016-03-26T13:19:03.167 回答
0

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

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

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

"Title"
"3219"
"Title"
"10549"
于 2016-03-26T13:15:40.650 回答