0

I need to extract a json in required format from input json. i'm using jayway json path library. How to achieve it ?

Input Json:

 { 
        "ccid": [
            {
                "id": 13,           
                "src": {
                    "sname": "XA-SXXD",
                    "lname": "John",
                    "identifier": 2,
                    "StatusCode": "C"
                }
            },
            {
                "id": 14,            
                "src": {
                    "sname": "XB-SXXD",
                    "lname": "Cena",
                    "identifier": 3,
                    "StatusCode": "C",
                }
            }
            ]
    }

Required Format:

[ { "id": "13", "sources": { "sname": "XA-SXXD", "lname": "John", "identifier": 2 } }, { "id": "14", "sources": { "sname": "XB-SXXD", "lname": "Cena", "identifier": 3 } }]

Query that i use:

$.ccid[*].src[?(@.identifier!=null)].['identifier','sname']

Output that i get:

[
   {
      "identifier" : 2,
      "sname" : "XA-SXXD"
   },
   {
      "identifier" : 3,
      "sname" : "XB-SXXD"
   }
]

Kindly help me to modify my query to get the required format. The string "sources" in the required format can be hardcoded.

user3383301
  • 1,891
  • 3
  • 21
  • 49

1 Answers1

0

I think I managed to solve this :)

$.ccid[*].[?(@.src.identifier!=null)].['id', 'src']

Give it a try.

Input tested on:

{ 
        "ccid": [
            {
                "id": 13,           
                "src": {
                    "sname": "XA-SXXD",
                    "lname": "John",
                    "StatusCode": "C"
                }
            },
            {
                "id": 14,            
                "src": {
                    "sname": "XB-SXXD",
                    "lname": "Cena",
                    "identifier": null,
                    "StatusCode": "C",
                }
            }
            ]
    }

Output received:

[
   {
      "id" : 13,
      "src" : {
         "sname" : "XA-SXXD",
         "lname" : "John",
         "StatusCode" : "C"
      }
   }
]

Only problem is saw is if identifier tag is not available it's essentially treated as not-null. Hence we are getting 13 as an output. But if value is explicitly null then it's fine. So the needs to be enhanced a bit more.

Hope this helps.

Himanshu Bhardwaj
  • 4,038
  • 3
  • 17
  • 36