I have a json array that looks as below –
[
{
"Code": "some code",
"Name": "some name",
"Country": "some country",
"Cost": "some cost",
"Type": "Some type"
},{
"Code": "some code",
"Name": "some name",
"Country": "some country",
"Cost": "some cost",
"Type": "Some type"
},{
"Code": "some code",
"Name": "some name",
"Country": "some country",
"Cost": "some cost",
"Type": "Some type"
}
]
I am trying print each json block on a new line with fields separated by '#'
Expected output
some code#some name#some country#some cost#some type
some code#some name#some country#some cost#some type
some code#some name#some country#some cost#some type
I’ve tried the code below which separates the content with '#'. However, it merges all blocks into a single line like this – some code#some name#some country#some cost#some type#some code#some name#some country#some cost#some type#some code#some name#some country#some cost#some type
cat contents.json | sed 's/^[ \t]*//;s/[ \t]*$//' | awk -F ': *' 'BEGIN { RS=",\n\"|\n}," } { gsub(/[\n\]\[\}]/,"",$2); if ($2) { printf("%s#", $2); } }'
Please could someone guide me to et this right?
>Solution :
Using jq (as tagged), values gets the field contents and join puts them together. The -r option ensures that raw text is being output (rather than JSON).
jq -r '.[] | values | join("#")' contents.json
some code#some name#some country#some cost#Some type
some code#some name#some country#some cost#Some type
some code#some name#some country#some cost#Some type
Update: Actually values is not even necessary as join, when applied to an object, will pull out the values itself.
jq -r '.[] | join("#")' contents.json
some code#some name#some country#some cost#Some type
some code#some name#some country#some cost#Some type
some code#some name#some country#some cost#Some type