1

I have the following returned to me as a response of a mocking tool I'm using.

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

I'd like to know how I can split each object into it's own file with the file named after the id of the object.

E.g:

bcf3559f-7ff7-406b-a4f1-6d3e9ac00e63.json

bcf3559f-7ff7-406b-a4f1-6d3e9ac00e63.json

I have got as far as this so far but can't get it over the line:

jq -c '.mappings = (.mappings[] | [.])' mappings.json |
  while read -r json ; do
  N=$((N+1))
  jq . <<< "$json"  > "tmp/file${N}.json"
done
2
  • 1
    what all the file's are supposed to have?, kindly share a sample for one id Commented Aug 22, 2018 at 16:15
  • A language with its own JSON library would be more appropriate for this task. Commented Aug 22, 2018 at 19:55

2 Answers 2

1

I'd recommend printing the id on one line, and the corresponding object on the next. For example:

jq -c '.mappings[] | .id, .' mappings.json |
    while read -r id ; do
    echo "id=$id"
    read -r json
      jq . <<< "$json"  > "tmp/${id}.json"
done
Sign up to request clarification or add additional context in comments.

Comments

0

I would write a simple Python script instead (or the equivalent in your favorite, general-purpose programming language).

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)

This would be more efficient and less error-prone, at least until jq gets some sort of output built-in:

# hypothetical
jq '.mappings[] | output("tmp/\(.id).json")' mappings.json

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.