Home > Software design >  How to create a specific result using JQ (jq parse json)
How to create a specific result using JQ (jq parse json)

Time:02-17

I have massive like this:

2254003131908096 39480500160 39763833120
2296334329577472 36713833920 37747166400
2297708719112192 39830499360 41430500640

Which JQ command should I use to get the result like this:

"2254003131908096": {
  {
    "exchange": "39480500160",
    "replication": "39763833120"
  }
}
    
"2296334329577472": {
  {
    "exchange": "36713833920",
    "replication": "39763833120"
  }
}
  
"2297708719112192": {  
  {
    "exchange": "39830499360",
    "replication": "41430500640"
  }
}

Help me please.

CodePudding user response:

Your sample output is invalid JSON. I assume you want to have one object with one field per input row.

Read in raw text using -R, then split by space using /, and reduce all the input to one object by setting the according fields.

jq -Rn '
  [inputs / " "] | reduce .[] as $line ({};
    .[$line[0]] = {exchange: $line[1], replication: $line[2]}
  )
'
{
  "2254003131908096": {
    "exchange": "39480500160",
    "replication": "39763833120"
  },
  "2296334329577472": {
    "exchange": "36713833920",
    "replication": "37747166400"
  },
  "2297708719112192": {
    "exchange": "39830499360",
    "replication": "41430500640"
  }
}

Demo

  • Related