使用 jq 解析 JSON 字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35154684/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Use jq to parse a JSON String
提问by Colin Grogan
I'm trying to get jqto parse a JSON structure like:
我正在尝试jq解析一个 JSON 结构,如:
{
"a" : 1,
"b" : 2,
"c" : "{\"id\":\"9ee ...\",\"parent\":\"abc...\"}\n"
}
That is, an element in the JSON is a string with escaped json.
也就是说,JSON 中的一个元素是一个带有转义 json 的字符串。
So, I have something along the lines of
$ jq [.c] myFile.json | jq [.id]
所以,我有一些类似的东西
$ jq [.c] myFile.json | jq [.id]
But that crashes with jq: error: Cannot index string with string
但这会崩溃 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?
这是因为 .c 的输出是一个字符串,而不是更多的 JSON。我如何让 jq 解析这个字符串?
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 jqto do this?
我最初的解决方案是使用 sed 替换所有转义字符(\":\",\",\"和\"),但这很麻烦,我认为有一种内置的方法jq可以做到这一点?
Thanks!
谢谢!
edit: Also, the jq version available here is:
编辑:另外,这里可用的 jq 版本是:
$ jq --version
jq version 1.3
I guess I could update it if required.
如果需要,我想我可以更新它。
回答by jwodder
回答by Casimir et Hippolyte
You can use the raw output (-r) that will unescape characters:
您可以使用将取消转义字符的原始输出 (-r):
jq -r .c myfile.json | jq .id
ADDENDUM: This has the advantage that it works in jq 1.3 and up; indeed, it should work in every version of jq that has the -r option.
附录:它的优势在于它适用于 jq 1.3 及更高版本;实际上,它应该适用于每个带有 -r 选项的 jq 版本。

