簡體   English   中英

在jq中將字符串轉換為json

[英]Convert string to json in jq

背景

我有一個 json 文件,其中包含一個對象中的 json 字符串:

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

我需要使用 json 命令行解釋器jq.response.text字符串的內容.response.text為 json 。

當我運行此命令時:

jq '.response.text | @json'

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

我得到了一些奇怪的轉義 json 字符串而不是 json,我可以通過這樣的東西訪問它: .response.text | @json | .recordID .response.text | @json | .recordID .記錄.response.text | @json | .recordID

我意識到@json函數將接受json 並輸出一個json 轉義字符串,所以必須有另一種方式,但@text似乎沒有做任何事情。

有什么方法可以將轉義的 json 字符串轉換為實際的 json,我可以使用如下命令解析它: jq '.response.text | @json | .title' jq '.response.text | @json | .title' jq '.response.text | @json | .title'並得到這個輸出: "Hello World"

使用fromjson

它將字符串解析為適當的 json 值。 tojson (和@json )相反,並采用 json 值並將其轉換為字符串。

所以你可以這樣做:

.response.text | fromjson.title

你也可以這樣做:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM