在jq中将字符串转换为json
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34340549/
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
Convert string to json in jq
提问by RJ-Adam
Background
背景
I have a json file that contains a string of json within an object:
我有一个 json 文件,其中包含一个对象中的 json 字符串:
{
"requestType": "POST",
"response": {
"size": 78,
"text": "{\"recordID\":123, \"title\":\"Hello World\", \"content\":\"Lorem ipsum...\"}"
}
}
I need to interperet the contents of the .response.textstring as json using the json command line interpereter, jq.
我需要.response.text使用 json 命令行解释器jq将字符串的内容解释为 json 。
When I run this command:
当我运行此命令时:
jq '.response.text | @json'
Output: "\"{\\\"recordID\\\":123, \\\"title\\\":\\\"Hello World\\\", \\\"content\\\":\\\"Lorem ipsum...\\\"}\""
输出: "\"{\\\"recordID\\\":123, \\\"title\\\":\\\"Hello World\\\", \\\"content\\\":\\\"Lorem ipsum...\\\"}\""
I get some weird escaped json string instead of json that I can access via something like this: .response.text | @json | .recordID.
我得到一些奇怪的转义JSON字符串,而不是JSON,我可以通过这样的访问:.response.text | @json | .recordID。
I realize that the @jsonfunction will take json and output a json escaped string, so there must be another way, but @textdoesn't seem to do anything.
我意识到该@json函数将采用 json 并输出一个 json 转义字符串,因此必须有另一种方法,但@text似乎没有做任何事情。
Question
题
Is there some way to convert a string of escaped json to actual json that I can parse with a command such as this: jq '.response.text | @json | .title'and get this output: "Hello World"?
有什么方法可以将转义的 json 字符串转换为实际的 json,我可以使用如下命令解析它:jq '.response.text | @json | .title'并获得此输出:"Hello World"?
回答by Jeff Mercado
回答by S P Arif Sahari Wibowo
You can also do this:
你也可以这样做:
jq -r '.response.text' | jq '.recordID'

