With the key: value data in input.txt, and the following program in tojson.jq:

[inputs | select(length>0) 
 | [splits(": *")]
 | {(.[0]): .[1]} ]
| add

the invocation:

jq -n -R -f tojson.jq input.txt

produces:

{
  "k1": "v1",
  "k2": "v2",
  "k3": "v3"
}
Answer from peak on Stack Overflow
Discussions

json - Convert an array of strings to a dictionary with JQ? - Stack Overflow
I can't figure out how to convert this to an arbitrarily-keyed object with jq. In order to properly use the array object, I need to convert it to a dictionary, something like {"arbitrary-key": "100.20.0.0/14"}, so that I can use it in Terraform like this: More on stackoverflow.com
🌐 stackoverflow.com
json - Create single dictionary with jq - Stack Overflow
I have the following input: [ { constant_id: 5, object_id: 2, object_type: 'delimited_file', name: 'data_file_pattern', value: 'list_of_orders.csv', insert_date: 2021-11-2... More on stackoverflow.com
🌐 stackoverflow.com
November 23, 2021
jq - Add key/value to json object - Unix & Linux Stack Exchange
Stack Exchange network consists of 183 Q&A communities including Stack Overflow, the largest, most trusted online community for developers to learn, share their knowledge, and build their careers · Stack Overflow for Teams is now called Stack Internal. Bring the best of human thought and AI ... More on unix.stackexchange.com
🌐 unix.stackexchange.com
question: how to concactenate values from list of dicts?
I have json like this: · I need output like map (name => time) More on github.com
🌐 github.com
5
November 25, 2015
🌐
Programming Historian
programminghistorian.org › en › lessons › json-and-jq
Reshaping JSON with jq | Programming Historian
May 24, 2016 - This lesson will begin with an overview of the basic operators of the jq query syntax. Next, you will learn progressively more complex ways of connecting these operators together. By the end of the lesson, you will understand how to combine basic operators to create queries that can reshape many types of JSON data.
Top answer
1 of 2
2

The following script uses the .ip_prefix as the key, thus perhaps avoiding the need for the sort|unique. It yields:

{
  "35.180.0.0/16": "35.180.0.0/16",
  "52.94.76.0/22": "52.94.76.0/22"
}

Script

#!/bin/bash

function data {
    cat <<EOF
{
  "syncToken": "1589917992",
  "createDate": "2020-05-19-19-53-12",
  "prefixes": [
    {
      "ip_prefix": "35.180.0.0/16",
      "region": "eu-west-3",
      "service": "AMAZON",
      "network_border_group": "eu-west-3"
    },
    {
      "ip_prefix": "52.94.76.0/22",
      "region": "us-west-2",
      "service": "AMAZON",
      "network_border_group": "us-west-2"
    }
    ]
}
EOF
}

data | jq '
  .prefixes 
  | map(select(.region | test("west"))
        | {(.ip_prefix): .ip_prefix} )
  | add '
2 of 2
0

There's a better option to get at the AWS IP ranges data in Terraform, which is to use the aws_ip_ranges data source, instead of trying to mangle things with the external data source and jq.

The example in the above linked documentation shows a similar, but also slightly more complex, thing to what you're trying to do here:

data "aws_ip_ranges" "european_ec2" {
  regions  = ["eu-west-1", "eu-central-1"]
  services = ["ec2"]
}

resource "aws_security_group" "from_europe" {
  name = "from_europe"

  ingress {
    from_port        = "443"
    to_port          = "443"
    protocol         = "tcp"
    cidr_blocks      = data.aws_ip_ranges.european_ec2.cidr_blocks
    ipv6_cidr_blocks = data.aws_ip_ranges.european_ec2.ipv6_cidr_blocks
  }

  tags = {
    CreateDate = data.aws_ip_ranges.european_ec2.create_date
    SyncToken  = data.aws_ip_ranges.european_ec2.sync_token
  }
}

To do your exact thing you would do something like this:

data "aws_ip_ranges" "us_west_2_amazon" {
  regions  = ["us_west_2"]
  services = ["amazon"]
}

resource "aws_default_security_group" "allow-mysql" {
  vpc_id = aws_vpc.main.id

  ingress {
    description = "MySQL"
    from_port   = 0
    to_port     = 0
    protocol    = "-1"
    cidr_blocks = data.aws_ip_ranges.us_west_2_amazon.cidr_blocks
  }
}

However, there are 2 things that are bad here.

The first, and most important, is that you're allowing access to your database from every IP address that AWS has in US-West-2 across all services. That means that anyone in the world is able to spin up an EC2 instance or Lambda function in US-West-2 and then have network access to your database. This is a very bad idea.

The second is that if that returns more than 60 CIDR blocks you are going to end up with more than 60 rules in your security group. AWS security groups have a limit of 60 security group rules per IP address type (IPv4 vs IPv6) and per ingress/egress:

You can have 60 inbound and 60 outbound rules per security group (making a total of 120 rules). This quota is enforced separately for IPv4 rules and IPv6 rules; for example, a security group can have 60 inbound rules for IPv4 traffic and 60 inbound rules for IPv6 traffic. A rule that references a security group or prefix list ID counts as one rule for IPv4 and one rule for IPv6.

From https://docs.aws.amazon.com/vpc/latest/userguide/amazon-vpc-limits.html#vpc-limits-security-groups

This is technically a soft cap and you can ask AWS to raise this limit in exchange for reducing the amount of security groups that can be applied to a network interface to keep the maximum amount of security group rules at or below 1000 per network interface. It's probably not something you want to mess around with though.

🌐
GitHub
github.com › jqlang › jq › issues › 1023
question: how to concactenate values from list of dicts? · Issue #1023 · jqlang/jq
November 25, 2015 - I tried to concatenate values with '.items[].created_time + .items[].link'', but i got n^2 elements (each time * each name fields) and without any separator.
Author   sc0rp10
🌐
Reddit
reddit.com › r/archlinux › how to do jq --slurp but for a dictionary
r/archlinux on Reddit: How to do jq --slurp but for a dictionary
August 11, 2024 - Hello, I need the output of the command hyprctl -j clients | jq -c 'sort_by(.at[1]) | group_by(.workspace.id) | .[] | {"\(.[].workspace.id)":[.[] | {"name": .initialClass, "active": (.focusHistoryID == 0)}]}' to be read into a dictionary, kinda like --slurp, with the number as name of each entry and the following array as it's value.
Find elsewhere
🌐
Jqlang
jqlang.github.io › jq › manual
jq 1.8 Manual
Once you understand the "," operator, you can look at jq's array syntax in a different light: the expression [1,2,3] is not using a built-in syntax for comma-separated arrays, but is instead applying the [] operator (collect results) to the expression 1,2,3 (which produces three different results). If you have a filter X that produces four results, then the expression [X] will produce a single result, an array of four elements. ... Like JSON, {} is for constructing objects (aka dictionaries or hashes), as in: {"a": 42, "b": 17}.
🌐
Exercism
exercism.org › tracks › jq › concepts › objects
Objects in jq on Exercism
$ echo "Jane" | jq -Rc '{.: 42}' jq: error: syntax error, unexpected '.' (Unix shell quoting issues?) at <top-level>, line 1: {.: 42} jq: error: May need parentheses around object key expression at <top-level>, line 1: {.: 42} jq: 2 compile errors $ echo "Jane" | jq -Rc '{(.): 42}' {"Jane":42}
Top answer
1 of 2
10

Like this:

$ jq '.compilerOptions.skipLibCheck=true' file.json
{
  "compileOnSave": false,
  "compilerOptions": {
    "baseUrl": "./",
    "skipLibCheck": true
  }
}
2 of 2
4

The easiest way to add the key with its value has been covered in another answer. That answer adds the key to the end of the list of keys in the compilerOptions object. Normally, the ordering of the keys does not matter, and if you need things ordered in a particular way, you will use an array. However, I'm noticing that you (for whatever reason) expect the key to be added first, before the existing baseUrl key.

We can add the key in that position by, instead of adding the new key to the existing object, instead, add the existing object's keys to the end of the new key. So given the existing JSON document,

{
  "compileOnSave": false,
  "compilerOptions": {
    "baseUrl": "./",
    "jerry": "Was a race car driver"
  }
}

... we may want to use

jq --argjson skipLibCheck true '.compilerOptions = $ARGS.named + .compilerOptions' file

Given our example document above, this would generate

{
  "compileOnSave": false,
  "compilerOptions": {
    "skipLibCheck": true,
    "baseUrl": "./",
    "jerry": "Was a race car driver"
  }
}

The $ARGS.named thing is an object which contains the key-value pairs defined with --arg and/or --argjson on the command line. In the example above, this would be {"skipLibCheck":true}. Note that the $ARGS feature was introduced after release 1.5 of jq.

With the older 1.5 release of jq, you may use

jq --argjson skipLibCheck true '.compilerOptions = { skipLibCheck: $skipLibCheck } + .compilerOptions' file

Use --arg instead of --argjson if you want the value to be the string true rather than the special boolean value true.

The following gives an alternative way of adding the key at the end (to what's mentioned in the other answer), which follows the same pattern as the above command. Note that I'm also switching to using --arg here to insert true as a string, just to show how that looks.

jq --arg skipLibCheck true '.compilerOptions += $ARGS.named' file

... which would give you

{
  "compileOnSave": false,
  "compilerOptions": {
    "baseUrl": "./",
    "jerry": "Was a race car driver",
    "skipLibCheck": "true"
  }
}

With the older 1.5 release of jq, you may use

jq --arg skipLibCheck true '.compilerOptions += { skipLibCheck: $skipLibCheck }' file
🌐
Bartificer
pbs.bartificer.net › pbs162
PBS 162: Altering Arrays & Dictionaries (jq)
March 2, 2024 - Add a key named displayName to each laureate dictionary. For people, it should contain their first & last names, and for organisations, just the organisation name. You’ll find the sample solution in the file pbs161-challengeSolution.jq in the instalment ZIP:
🌐
Zendesk Developer Docs
developer.zendesk.com › documentation › integration-services › developer-guide › jq-cheat-sheet
jq cheat sheet | Zendesk Developer Docs
This article provides example jq expressions you can use in the expr parameter. If you're new to jq, you can use these examples as a starting point when writing your own expressions. You can test the expressions using the jq play site or the jq command-line tool.
🌐
GitHub
gist.github.com › joar › 776b7d176196592ed5d8
Add a field to an object with JQ · GitHub
This is the actual output: $ echo '{"hello": "world"}' | jq --arg foo bar '. + {hello: ("not" + $foo)}'
🌐
DigitalOcean
digitalocean.com › community › tutorials › how-to-transform-json-data-with-jq
How To Transform JSON Data with jq | DigitalOcean
September 23, 2025 - In this step, you will set up your sample input file and test the setup by running a jq command to generate an output of the sample file’s data. jq can take input from either a file or a pipe. You will use the former. You’ll begin by generating the sample file. Create and open a new file named seaCreatures.json using your preferred editor (this tutorial uses nano):
🌐
GitHub
gist.github.com › olih › f7437fb6962fb3ee9fe95bda8d2c8fa4
jq Cheet Sheet · GitHub
I wrote a python script to do this, but figured this could be done with jq and/or other bash built-ins.
🌐
Grimoire
grimoire.carcano.ch › the grimoire of a modern linux professional › blog › dev-ops tools › pillars › json and jq in a nutshell
JSON and jq in a nuthsell: all a professional must know
November 14, 2024 - NUMBERS='"numbers": [ 1, 0.3, 2.5, -0.9 ]' echo "{$NUMBERS}" | jq '.numbers | sort' ... Conversely , if we need the maximum element we can pipe the output of the filter to the "max" function: ... Although this is not very common, there may be situations that require you to convert a list into a list of dictionaries: for example you can turn a list into a list of dictionaries so that you can then use the "select" function to know if the list does actually contain a given value.