繁体   English   中英

bash将数组拆分为具有动态名称的单独文件

[英]bash split array into separate files with dynamic name

作为对我正在使用的模拟工具的回应,我将以下内容返回给我。

{
  "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

我建议在一行打印 id,在下一行打印相应的对象。 例如:

jq -c '.mappings[] | .id, .' mappings.json |
    while read -r id ; do
    echo "id=$id"
    read -r json
      jq . <<< "$json"  > "tmp/${id}.json"
done

我会改写一个简单的 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.json

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM