在jq中将字符串转换为json [英] Convert string to json in jq

查看:784
本文介绍了在jq中将字符串转换为json的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个json文件,其中包含一个对象内的json字符串:

I have a json file that contains a string of json within an object:

{
    "requestType": "POST",
    "response": {
        "size": 78,
        "text": "{\"recordID\":123, \"title\":\"Hello World\", \"content\":\"Lorem ipsum...\"}"
    }
}

我需要使用json命令行中介程序 jq .

I need to interperet the contents of the .response.text string as json using the json command line interpereter, jq.

当我运行此命令时:

jq '.response.text | @json'

输出:"\"{\\\"recordID\\\":123, \\\"title\\\":\\\"Hello World\\\", \\\"content\\\":\\\"Lorem ipsum...\\\"}\""

我得到了一些奇怪的转义json字符串,而不是我可以通过类似以下方式访问的json:.response.text | @json | .recordID.

I get some weird escaped json string instead of json that I can access via something like this: .response.text | @json | .recordID.

我意识到@json函数将使用json并输出json转义的字符串,因此必须有另一种方法,但是@text似乎没有任何作用.

I realize that the @json function will take json and output a json escaped string, so there must be another way, but @text doesn't seem to do anything.

是否有某种方法可以将转义的json字符串转换为我可以使用以下命令解析的实际json:jq '.response.text | @json | .title'并获得以下输出:"Hello World"?

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值. tojson(和@json)则相反,并获取一个json值并将其转换为字符串.

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.

所以您可以这样做:

.response.text | fromjson.title

这篇关于在jq中将字符串转换为json的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆