gayashanbc
gayashanbc

Reputation: 1024

jq - using map function to preserve the currently sorted order of properties

I have the following JSON named as my.json.

[
  {
    "action": "copy",
    "artifact_location": "one foo one"
  },
  {
    "action": "copy",
    "artifact_location": "one bar one"
  },
  {
    "action": "remove",
    "artifact_location": "two foo two"
  }
]

I'm trying to understand the usage of the map function in jq version 1.3.

Later, I intend the use this logic (i.e. map function) for a complex jq filter to preserve the currently sorted order of properties in each object as --sort-keys option is not available in jq version 1.3.

My goal is to output the content of the my.json file as it as after using the map function.

So far, I have come up with the following jq command based on the answers [1] and [2].

jq -r 'map(to_entries | map({(.key): .value}))' my.json

Which gives me the following output.

[
  [
    {
      "action": "copy"
    },
    {
      "artifact_location": "one foo one"
    }
  ],
  [
    {
      "action": "copy"
    },
    {
      "artifact_location": "one bar one"
    }
  ],
  [
    {
      "action": "remove"
    },
    {
      "artifact_location": "two foo two"
    }
  ]
]

If I combine the add function as follows.

jq -r 'map(to_entries | map({(.key): .value}) | add )' my.json

It changes the previously sorted order of properties similar to the output below.

[
  {
    "artifact_location": "one foo one",
    "action": "copy"
  },
  {
    "artifact_location": "one bar one",
    "action": "copy"
  },
  {
    "artifact_location": "two foo two",
    "action": "remove"
  }
]

What am I missing here?

Upvotes: 0

Views: 958

Answers (1)

peak
peak

Reputation: 116919

jq 1.3 makes no guarantees about the ordering of keys within an object. It's really as simple as that, though map itself has nothing to do with the reordering you've noticed.

Bear in mind also that that version of jq is very old and should be considered obsolete.

However, within the confines of jq 1.3, you might be able to do whatever it is you are really trying to do, but any example of keys being reordered will just illustrate the previous point.

Upvotes: 2

Related Questions