使用jq解析JSON字符串 [英] Use jq to parse a JSON String
问题描述
我正在尝试获取jq
来解析JSON结构,例如:
{
"a" : 1,
"b" : 2,
"c" : "{\"id\":\"9ee ...\",\"parent\":\"abc...\"}\n"
}
也就是说,JSON中的元素是带有转义json的字符串.
所以,我有一些类似的东西
$ jq [.c] myFile.json | jq [.id]
但是这会随着jq: error: Cannot index string with string
这是因为.c的输出是一个字符串,而不是JSON. 如何让jq解析此字符串?
我最初的解决方案是使用sed替换所有转义字符(\":\"
,\",\"
和\"
),但这很麻烦,我认为jq
中内置了一种方法来做到这一点? >
谢谢!
另外,这里可用的jq版本是:
$ jq --version
jq version 1.3
我想我可以根据需要对其进行更新.
jq具有 fromjson
内置于此:
jq '.c | fromjson | .id' myFile.json
fromjson
是在1.4版中添加的.
I'm trying to get jq
to parse a JSON structure like:
{
"a" : 1,
"b" : 2,
"c" : "{\"id\":\"9ee ...\",\"parent\":\"abc...\"}\n"
}
That is, an element in the JSON is a string with escaped json.
So, I have something along the lines of
$ jq [.c] myFile.json | jq [.id]
But that crashes with jq: error: Cannot index string with string
This is because the output of .c is a string, not more JSON. How do I get jq to parse this string?
My initial solution is to use sed to replace all the escape chars (\":\"
, \",\"
and \"
) but that's messy, I assume there's a way built into jq
to do this?
Thanks!
edit: Also, the jq version available here is:
$ jq --version
jq version 1.3
I guess I could update it if required.
jq has the fromjson
builtin for this:
jq '.c | fromjson | .id' myFile.json
fromjson
was added in version 1.4.
这篇关于使用jq解析JSON字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!