我将以下内容作为我正在使用的模拟工具的响应返回给我。
{
"mappings" : [
{
"id" : "bcf3559f-7ff7-406b-a4f1-6d3e9ac00e63",
"name" : "Hellow world 2",
"request" : {
"url" : "/hello-world-2",
"method" : "POST"
},
"response" : {
"status" : 200,
"body" : "\nBody content for stub 3\n\n",
"headers" : { }
},
"uuid" : "bcf3559f-7ff7-406b-a4f1-6d3e9ac00e63",
"persistent" : true,
"priority" : 5
},
{
"id" : "9086b24f-4f5e-465a-bbe5-73bbfb82cd5c",
"name": "Hello world",
"request" : {
"url" : "/hello-world",
"method" : "ANY"
},
"response" : {
"status" : 200,
"body" : "Hi!"
},
"uuid" : "9086b24f-4f5e-465a-bbe5-73bbfb82cd5c"
} ]
}我想知道如何将每个对象拆分到它自己的文件中,该文件以对象的id命名。
例如:
bcf3559f-7ff7-406b-a4f1-6d3e9ac00e63.json
bcf3559f-7ff7-406b-a4f1-6d3e9ac00e63.json
到目前为止,我已经做到了这一点,但我不能让它越过这条线:
jq -c '.mappings = (.mappings[] | [.])' mappings.json |
while read -r json ; do
N=$((N+1))
jq . <<< "$json" > "tmp/file${N}.json"
done发布于 2018-08-23 02:46:11
我建议在一行中打印id,在下一行中打印相应的对象。例如:
jq -c '.mappings[] | .id, .' mappings.json |
while read -r id ; do
echo "id=$id"
read -r json
jq . <<< "$json" > "tmp/${id}.json"
done发布于 2018-08-23 04:02:02
我会编写一个简单的Python脚本(或者用您最喜欢的通用编程语言编写的等价物)。
import sys, json
d = json.load(sys.stdin):
for o in d['mappings']:
with open(os.path.join('tmp', o['id'] + '.json'), 'w') as f:
json.dump(o, f)这会更高效,更不容易出错,至少在jq获得某种内置的output之前是这样的:
# hypothetical
jq '.mappings[] | output("tmp/\(.id).json")' mappings.jsonhttps://stackoverflow.com/questions/51970861
复制相似问题