Shang Jian Ding
Shang Jian Ding

Reputation: 2126

update value of a map of objects

With jq, how can I transform the following:

{
  "root": {
    "branch1": {
      "leaf": 1
    },
    "branch2": {
      "leaf": 2
    },
    "branch3": {
      "leaf": 3
    }
  },
  "another-root": {
      "branch": 123
  },
  "foo": "bar"
}

to this:

{
  "root": {
    "branch1": {
      "leaf": "updated"
    },
    "branch2": {
      "leaf": "updated"
    },
    "branch3": {
      "leaf": "updated"
    }
  },
  "another-root": {
      "branch": 123
  },
  "foo": "bar"
}

Upvotes: 1

Views: 73

Answers (2)

Valentin Micu
Valentin Micu

Reputation: 73

First you need to parse the json and then modify the resulting object as required using for ... in statement (example below)

const flatJSON = '{"root":{"branch1":{"leaf":1},"branch2":{"leaf":2},"branch3":{"leaf":3}},"another-root":{"branch":123},"foo":"bar"}';

const parsedJSON = JSON.parse(flatJSON);
const root = parsedJSON.root;

for (let property in root) {
  root[property].leaf = "updated"; (or root[property]["leaf"] = "updated";)
}

If you want to use jquery you have to replace for ... in statement with jQuery.each() method that iterates over both objects and arrays.

Don't forget to convert it back to json with JSON.stringify() method (if required).

Hope that this helps. All the best.

Upvotes: -1

Shang Jian Ding
Shang Jian Ding

Reputation: 2126

🤦 Apparently [] can be used on object too. I had though it was only for lists.

The following was all I needed.

.root[].leaf="updated"

Upvotes: 2

Related Questions