Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Add serial number to JSON

I’ve a JSON:

[
  {
    "id": 3
  },
  {
    "id": 1
  },
  {
    "id": 2
  }
]

I want to add additional key called order_id to all objects in this json and set value as objects order in json (serial number). First object in json should have order_id = 1, etc…. Amount of objects in json can be different, it’s just example.

I expect this json:
Expected result:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[
  {
    "id": 3,
    "order_id": 1
  },
  {
    "id": 1,
    "order_id": 2
  },
  {
    "id": 2,
    "order_id": 3
  }
]

>Solution :

You can use two stages of transformations such as

[ // replicate each objects' index within the array
  //(they always start from 0 and increments by 1)
  {
    "operation": "shift",
    "spec": {
      "*": {
        "*": "[#2].&", // replicate all existing attributes
        "$": "[#2].order_id"
      }
    }
  },
  { // increment each of those indexes by 1
    "operation": "modify-overwrite-beta",
    "spec": {
      "*": {
        "order_id": "=intSum(1,@(1,&))"
      }
    }
  },
  { // sort by attributes' names
    "operation": "sort"
  }
]

the demo on the site http://jolt-demo.appspot.com/ is :

enter image description here

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading