Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Print json block from a json array on new line joined by '#'

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Demo


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

Demo

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading