简体   繁体   中英

How to get the complete object / array with jq?

I'm running:

$ jq ".environments[] | select(.name | contains(\"docker\")) | .database.database_config.host = \"${DGRAPHIP}\"" weaviate.conf.json

on this file: https://github.com/weaviate/weaviate/blob/develop/weaviate.conf.json

The output of this is (if DGRAPHIP = 1.2.3.4 ):

{
  "name": "docker",
  "database": {
    "name": "dgraph",
    "database_config": {
      "host": "1.2.3.4", <== THIS IS GOOD!
      "port": 9080
    }
  },
  "schemas": {
    "Thing": "https://raw.githubusercontent.com/weaviate/weaviate-semantic-schemas/master/weaviate-Thing-ontology-s
chema_org.min.json",
    "Action": "https://raw.githubusercontent.com/weaviate/weaviate-semantic-schemas/master/weaviate-Action-ontology
-schema_org.min.json"
  },
  "mqttEnabled": false
}

This is not the desired outcome, I would like the outcome to be encapsulated like:

{
    "environments": [{
        RESULTS
    }]
}

Simple adjustment:

jq --arg dgraphip "1.2.3.4" '{"environments" : .environments 
 | map(select(.name | contains("docker")) 
 | .database.database_config.host = $dgraphip)}' weaviate.conf.json

The output:

{
  "environments": [
    {
      "name": "docker",
      "database": {
        "name": "dgraph",
        "database_config": {
          "host": "1.2.3.4",
          "port": 9080
        }
      },
      "schemas": {
        "Thing": "https://raw.githubusercontent.com/weaviate/weaviate-semantic-schemas/master/weaviate-Thing-ontology-schema_org.min.json",
        "Action": "https://raw.githubusercontent.com/weaviate/weaviate-semantic-schemas/master/weaviate-Action-ontology-schema_org.min.json"
      },
      "mqttEnabled": false
    }
  ]
}

Here is another approach which uses update assignment |= with map

.environments |= map(      
     select(.name | contains("docker"))
   | .database.database_config.host = "1.2.3.4"
) 

Sample Run (assumes data in data.json )

$ jq -M '.environments |= map(select(.name | contains("docker")) | .database.database_config.host = "1.2.3.4")' data.json
{
  "environments": [
    {
      "name": "docker",
      "database": {
        "name": "dgraph",
        "database_config": {
          "host": "1.2.3.4",
          "port": 9080
        }
      },
      "schemas": {
        "Thing": "https://raw.githubusercontent.com/weaviate/weaviate-semantic-schemas/master/weaviate-Thing-ontology-schema_org.min.json",
        "Action": "https://raw.githubusercontent.com/weaviate/weaviate-semantic-schemas/master/weaviate-Action-ontology-schema_org.min.json"
      },
      "mqttEnabled": false
    }
  ]
}

Try it online at jqplay.org

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM