首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >bash将数组拆分为具有动态名称的单独文件

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

Stack Overflow用户
提问于 2018-08-23 00:01:49
回答 2查看 84关注 0票数 1

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

代码语言:javascript
复制
{
  "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

到目前为止,我已经做到了这一点,但我不能让它越过这条线:

代码语言:javascript
复制
jq -c '.mappings = (.mappings[] | [.])' mappings.json |
  while read -r json ; do
  N=$((N+1))
  jq . <<< "$json"  > "tmp/file${N}.json"
done
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-08-23 02:46:11

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

代码语言:javascript
复制
jq -c '.mappings[] | .id, .' mappings.json |
    while read -r id ; do
    echo "id=$id"
    read -r json
      jq . <<< "$json"  > "tmp/${id}.json"
done
票数 1
EN

Stack Overflow用户

发布于 2018-08-23 04:02:02

我会编写一个简单的Python脚本(或者用您最喜欢的通用编程语言编写的等价物)。

代码语言:javascript
复制
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之前是这样的:

代码语言:javascript
复制
# hypothetical
jq '.mappings[] | output("tmp/\(.id).json")' mappings.json
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51970861

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档