我试图解析从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=文本表示)?


当前回答

对于更复杂的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.

其他回答

你可以尝试这样做-

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

使用Ruby进行解析(解释器默认在/usr/bin/ruby中可用于所有macOS版本):

echo "${JSON}" | /usr/bin/ruby -e 'require "json"; puts JSON.parse(http://STDIN.read)["key1"]["nested_key_2"];'

你可以使用bashJson

它是Python JSON模块的包装器,可以处理复杂的JSON数据。

让我们考虑来自test.json文件的示例JSON数据

{
    "name":"Test tool",
    "author":"hack4mer",
    "supported_os":{
        "osx":{
            "foo":"bar",
            "min_version" : 10.12,
            "tested_on" : [10.1,10.13]
        },
        "ubuntu":{
            "min_version":14.04,
            "tested_on" : 16.04
        }
    }
}

下面的命令从这个示例JSON文件读取数据

./bashjson.sh test.json name

打印:测试工具

./bashjson.sh test.json supported_os osx foo

打印:酒吧

./bashjson.sh test.json supported_os osx tested_on

打印:[10.1,10.13]

下面是shell书呆子使用POSIX shell(带local)和egrep的答案:JSON.sh, 4.7 KB。

这个东西有很多测试用例,所以它应该是正确的。它也是可管道的。它用于Bash的包管理器bpkg。

使用Python使用Bash

在.bashrc文件中创建一个Bash函数:

function getJsonVal () {
    python -c "import json,sys;sys.stdout.write(json.dumps(json.load(sys.stdin)$1))";
}

Then

curl 'http://twitter.com/users/username.json' | getJsonVal "['text']"

输出:

My status

下面是相同的函数,但是带有错误检查。

function getJsonVal() {
   if [ \( $# -ne 1 \) -o \( -t 0 \) ]; then
       cat <<EOF
Usage: getJsonVal 'key' < /tmp/
 -- or --
 cat /tmp/input | getJsonVal 'key'
EOF
       return;
   fi;
   python -c "import json,sys;sys.stdout.write(json.dumps(json.load(sys.stdin)$1))";
}

其中$# -ne 1确保至少有一个输入,而-t 0确保从管道重定向。

这个实现的好处是,您可以访问嵌套的JSON值并返回JSON内容!=)

例子:

echo '{"foo": {"bar": "baz", "a": [1,2,3]}}' |  getJsonVal "['foo']['a'][1]"

输出:

2

如果你想要更漂亮,你可以把数据打印出来:

function getJsonVal () {
    python -c "import json,sys;sys.stdout.write(json.dumps(json.load(sys.stdin)$1, sort_keys=True, indent=4))";
}

echo '{"foo": {"bar": "baz", "a": [1,2,3]}}' |  getJsonVal "['foo']"
{
    "a": [
        1,
        2,
        3
    ],
    "bar": "baz"
}