为什么jsontool不会解析我的数组?

时间:2014-07-11 14:26:49

标签: json bash

我在解析这个包含数组作为其最外层元素的json时遇到了问题:

response=[ { "__type": "File", "name": "...tfss-ea51ec70-d3a8-45e5-abbf-294f2c2c81f0-myPicture.jpg", "url": "http://files.parse.com/ac3f079b-cacb-49e9-bd74-8325f993f308/...tfss-ea51ec70-d3a8-45e5-abbf-294f2c2c81f0-myPicture.jpg" } ]

for blob in $response
do
    url=$(echo $blob | json url)
done

但是这最后一次json解析会产生一系列错误:

json: error: input is not JSON: Bad object at line 2, column 1:

    ^

我是否需要做一些特别的事情来将JSON数组转换为bash数组,反之亦然?

2 个答案:

答案 0 :(得分:3)

你应该引用reponse的值来保护它免受shell试图解释它:

response='[ { "__type": "File", "name": "...tfss-ea51ec70-d3a8-45e5-abbf-294f2c2c81f0-myPicture.jpg", "url": "http://files.parse.com/ac3f079b-cacb-49e9-bd74-8325f993f308/...tfss-ea51ec70-d3a8-45e5-abbf-294f2c2c81f0-myPicture.jpg" } ]'

并且你不能期望shell能够解析JSON,因此for blob in $response无法解决问题。根据{{​​3}},使用-a应该处理数组:

while read url ; do
   # use $url here...
done < <(echo "$response" | json -a url)

答案 1 :(得分:0)

将你的json放入一个文件并通过jsontool管道之后它运行得很好,所以我猜你的文件有一些奇怪的空白在jsontool中打破。

请改为尝试:

cat your_file.json | sed 's/[[:space:]]\+$//' | json
相关问题