Artem Mayer
Artem Mayer

Reputation: 25

How to create a specific result using JQ (jq parse json)

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.

Upvotes: 0

Views: 99

Answers (2)

Logan Lee
Logan Lee

Reputation: 987

You can use reduce.

Filter

reduce (inputs / " " ) as [$k,$e,$r] ({}; .+{($k):{exchange:$e,replication:$r}})

Input

2254003131908096 39480500160 39763833120
2296334329577472 36713833920 37747166400
2297708719112192 39830499360 41430500640

Output

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

Demo

https://jqplay.org/s/9uugFhWQtt

Upvotes: 0

pmf
pmf

Reputation: 36088

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

Upvotes: 1

Related Questions