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

Viewed 152

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?

2 Answers

Using jq, the join builtin, when applied to an object, will pull out the field values and concatenate them using a separator string. The -r option ensures that raw text is being output (rather than JSON).

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


Update: If in the input objects the keys cannot be guaranteed to always be in the same order, just specify their order explicitly using an array.

jq -r '.[] | [.Code,.Name,.Country,.Cost,.Type] | 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

I won't recommend Miller over jq for dealing with JSON, but in this case the JSON is compatible and mlr powerful features could become handy for further processing of the input:

mlr --ijson --ocsv --ofs '#' unsparsify file.json
Code#Name#Country#Cost#Type
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

notes:

  • You can avoid displaying the header with the -N option
  • Unordered or missing keys in the JSON objects won't break the output
Related