Home > Net >  How to use jq to merge a list of dictionaries into one dictionary
How to use jq to merge a list of dictionaries into one dictionary

Time:04-15

I'm developing jq expressions on the command line. (I plan to use the expression with pyjq in python to parse http requests.)

The following command line:

$ cat some.json | jq '.collection.rows[].rowAnswers | map({ (.refCode) : .answers[0].responseText }) '

Results in two items.

[
  {
    "NAME": "some_name1"
  },
  {
    "CODE": "code1"
  },
  {
    "SERVER"": "server1"
  }
]
[
  {
    "NAME": "name2"
  },
  {
    "CODE": "code2"
  },
  {
    "SERVER"": "server2"
  }
]

This is a nice intermediate step. I'd like to merge each list of dictionaries into one dictionary. I'd like the final result to be:

{
    "NAME": "some_name1"
    "CODE": "code1"
    "SERVER"": "server1"
}
{
    "NAME": "name2"
    "CODE": "code2"
    "SERVER"": "server2"
}

If that's too difficult, then [merge_dict][merge_dict] is good too.

There won't be any key collisions. Also, this is simplified output. I'd like an expression that merges all kv-pairs into one dictionary. I don't want to hardcode the actual name of the keys in the expression.

Thanks.

CodePudding user response:

Based on your description, it would seem that could achieve what you describe as your "final result" just by adding add to your pipeline.

  • Related