在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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 18:11:20  来源:igfitidea点击:

Convert string to json in jq

jsoncommand-linejq

提问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

Use fromjson.

使用fromjson.

It parses a string to its appropriate json value. tojson(and @json) goes the other way around and takes a json value and converts it to a string.

它将字符串解析为适当的 json 值。 tojson(和@json) 反过来,接受一个 json 值并将其转换为字符串。

So you could do this:

所以你可以这样做:

.response.text | fromjson.title

回答by S P Arif Sahari Wibowo

You can also do this:

你也可以这样做:

jq -r '.response.text' | jq '.recordID'