Reputation: 5141
I have a json data as below. Need to grep the value and export it into a new file.
{
"Data":
[
"User": [
{"Name": "Solomon", "Age":20},
{"Name": "Absolom", "Age":30},
]
"Country": [
{"Name" : "US", "Resident" : "Permanent"},
{"Name" : "UK", "Resident" : "Temporary"}
]]}
Expected result,
Need to grep the value of "User" and export it to a new file User.json
User.json
"User": [
{"Name": "Solomon", "Age":20},
{"Name": "Absolom", "Age":30},
]
And again need to grep "Country" and export to Country.json
Country.json
"Country": [
{"Name" : "US", "Resident" : "Permanent"},
{"Name" : "UK", "Resident" : "Temporary"}
]
Was trying with sed
, but am getting incorrect results
sed -e 's/.*"User"\(.*\)].*/\1/' Data.json > Users.json
Since there are many special characters ]/[/{/}
, not sure how to properly grep a value and export it to a new file.
Any suggestion would be really helpful
Upvotes: 0
Views: 116
Reputation: 26925
Your input is not a valid JSON, however, for parsing JSON you could use jq, for example, modifying your input a little bit, give a try to this:
$ echo '{
"Data":[
{
"User":[
{
"Name":"Solomon",
"Age":20
},
{
"Name":"Absolom",
"Age":30
}
],
"Country":[
{
"Name":"US",
"Resident":"Permanent"
},
{
"Name":"UK",
"Resident":"Temporary"
}
]
}
]
}'| jq -cr .'Data[] | with_entries(select(.key == "User"))';
It will output (for user):
{"User":[{"Name":"Solomon","Age":20},{"Name":"Absolom","Age":30}]}
And if you use | jq -cr .'Data[] | with_entries(select(.key == "Country"))';
(for country)
{"Country":[{"Name":"US","Resident":"Permanent"},{"Name":"UK","Resident":"Temporary"}]}
This is only one way of many possible, but I hope it can give you an idea.
Upvotes: 0
Reputation: 141040
With enough luck you can use GNU sed with -z
option and filter the content up until a closing ]
assuming there will be no ]
in the strings:
sed -z 's/.*\("User":[^]]*]\).*/\1\n/'
sed -z 's/.*\("Country":[^]]*]\).*/\1\n/'
Upvotes: 1