我试图解析从curl请求返回的JSON,就像这样:

curl 'http://twitter.com/users/username.json' |
    sed -e 's/[{}]/''/g' | 
    awk -v k="text" '{n=split($0,a,","); for (i=1; i<=n; i++) print a[i]}'

上面将JSON划分为多个字段,例如:

% ...
"geo_enabled":false
"friends_count":245
"profile_text_color":"000000"
"status":"in_reply_to_screen_name":null
"source":"web"
"truncated":false
"text":"My status"
"favorited":false
% ...

我如何打印一个特定的字段(由-v k=文本表示)?


当前回答

你可以使用jshon:

curl 'http://twitter.com/users/username.json' | jshon -e text

其他回答

有XML文件的人可能想看看我的Xidel。它是一个命令行界面,无依赖的JSONiq处理器。(也就是说,它还支持XQuery进行XML或JSON处理。)

问题中的例子是:

 xidel -e 'json("http://twitter.com/users/username.json")("name")'

或者用我自己的非标准扩展语法:

 xidel -e 'json("http://twitter.com/users/username.json").name'

对于更复杂的JSON解析,我建议使用Python jsonpath模块(Stefan Goessner) -

Install it - sudo easy_install -U jsonpath Use it - Example file.json (from http://goessner.net/articles/JsonPath) - { "store": { "book": [ { "category": "reference", "author": "Nigel Rees", "title": "Sayings of the Century", "price": 8.95 }, { "category": "fiction", "author": "Evelyn Waugh", "title": "Sword of Honour", "price": 12.99 }, { "category": "fiction", "author": "Herman Melville", "title": "Moby Dick", "isbn": "0-553-21311-3", "price": 8.99 }, { "category": "fiction", "author": "J. R. R. Tolkien", "title": "The Lord of the Rings", "isbn": "0-395-19395-8", "price": 22.99 } ], "bicycle": { "color": "red", "price": 19.95 } } } Parse it (extract all book titles with price < 10) - cat file.json | python -c "import sys, json, jsonpath; print '\n'.join(jsonpath.jsonpath(json.load(sys.stdin), 'store.book[?(@.price < 10)].title'))" Will output - Sayings of the Century Moby Dick Note: The above command line does not include error checking. For a full solution with error checking, you should create a small Python script, and wrap the code with try-except.

不幸的是,使用grep的得票最多的答案返回完整的匹配,这在我的场景中不起作用,但如果您知道JSON格式将保持不变,您可以使用向后和向前查找来提取所需的值。

# echo '{"TotalPages":33,"FooBar":"he\"llo","anotherValue":100}' | grep -Po '(?<="FooBar":")(.*?)(?=",)'
he\"llo
# echo '{"TotalPages":33,"FooBar":"he\"llo","anotherValue":100}' | grep -Po '(?<="TotalPages":)(.*?)(?=,)'
33
#  echo '{"TotalPages":33,"FooBar":"he\"llo","anotherValue":100}' | grep -Po '(?<="anotherValue":)(.*?)(?=})'
100

你可以尝试这样做-

curl -s 'http://twitter.com/users/jaypalsingh.json' | 
awk -F=":" -v RS="," '$1~/"text"/ {print}'

Niet是一个工具,可以帮助您直接在shell或Bash CLI中从JSON或YAML文件中提取数据。

pip install niet

考虑一个名为project的JSON文件。Json,包含以下内容:

{
  project: {
    meta: {
      name: project-sample
    }
}

你可以这样使用Niet:

PROJECT_NAME=$(niet project.json project.meta.name)
echo ${PROJECT_NAME}

输出:

project-sample