gpt4 book ai didi

json - Bash,管道解析和格式化 json(瘦身)

转载 作者:太空宇宙 更新时间:2023-11-04 09:26:22 26 4
gpt4 key购买 nike

我有一个 bash 脚本输出这样的 json:

 {
"name": "some",
"desc": "this is a desc",
"env": "this is an env type",
"dd": {
"one": "rr",
"two": "aa"
},
"url": "http://someurl",
//etc......
}

我想在我的脚本中传递一个新命令,以返回最终的 json 输出:

{
"name": "some",
"env": "this is an env type",
"dd": {
"one": "rr",
"two": "aa"
}
}

我如何在不安装像 jq 这样的新工具/库的情况下实现这一目标 等。

有什么线索吗?

最佳答案

我知道您已经规定在没有外部工具的情况下执行此操作,但希望这会改变您的想法:

jq '{ name, env, dd }' file.json

这很简单!

jq is very easy to obtain .

一个快速而肮脏的 python 脚本也可以工作:

import sys
import json

with open(sys.argv[1]) as file:
obj = json.load(file)
print json.dumps({ key: obj[key] for key in ("name", "env", "dd") })

可以像python script.py file.json一样运行。要改进格式,您可以将额外的参数传递给 json.dumps ( see the docs )。

关于json - Bash,管道解析和格式化 json(瘦身),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35922123/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com