如何使用 jq(或其他替代方法)解析 JSON 字符串? [英] how to parse a JSON String with jq (or other alternatives)?

查看:20
本文介绍了如何使用 jq(或其他替代方法)解析 JSON 字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图让 jq 解析一个 JSON 结构,如:

I'm trying to get jq to parse a JSON structure like:

{
  "a" : 1,
  "b" : 2,
  "c" : "{"id":"9ee ...","parent":"abc..."}
"
}

也就是说,JSON 中的一个元素是一个带有转义 json 的字符串.

That is, an element in the JSON is a string with escaped json.

所以,我有一些类似的东西$ jq [.c] myFile.json |jq [.id]

So, I have something along the lines of $ jq [.c] myFile.json | jq [.id]

但是用 jq 崩溃了:错误:无法用字符串索引字符串

这是因为 .c 的输出是一个字符串,而不是更多的 JSON.我如何让 jq 解析这个字符串?

This is because the output of .c is a string, not more JSON. How do I get jq to parse this string?

我最初的解决方案是使用 sed 替换所有转义字符(":", "," and "code>) 但这很麻烦,我认为 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 jq to do this?

谢谢!

此外,这里可用的 jq 版本是:

edit: Also, the jq version available here is:

$ jq --version
jq version 1.3

如果需要,我想我可以更新它.

I guess I could update it if required.

推荐答案

jq 有 fromjson 为此内置:

jq has the fromjson builtin for this:

jq '.c | fromjson | .id' myFile.json

fromjson 是在 1.4 版本中添加的.

fromjson was added in version 1.4.

这篇关于如何使用 jq(或其他替代方法)解析 JSON 字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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