Home > Software engineering >  Print json block from a json array on new line joined by '#'
Print json block from a json array on new line joined by '#'

Time:02-01

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?

CodePudding user response:

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

CodePudding user response:

I won't recommend mlr over jq for dealing with JSON, but in this case its 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

note: You can remove the header with the -N option

The advantage of this solution is that unordered or missing keys in the JSON objects won't jinx the output. Yet, if the JSON has a more complex structure then mlr won't be able to convert it.

  •  Tags:  
  • Related