-2

Is there any way to insert a JSON object in the middle of another JSON object using jsonPath? I'm using Javascript in the Postman test script after I recieve a JSON object as a response, and I need to insert JSON data in the middle of the response. I can access the part of the response I want using "$..decision[0]". Is there a way to add data using "$..decision[1]" so that this:

 ...
"decision": [
            {
                "var1": 43,
                "var2": 1,
            }
        ],...

becomes this:

 ...
"decision": [
            {
                "var1": 43,
                "var2": 1
            },
            {
                "foo1": "true",
                "foo2": "false"
            }
        ],...

If I can't, is there another simple way to append data into the middle of a JSON object?

S. Liu
  • 11
  • 5
  • what have you tried? how do you create the response data? – mast3rd3mon May 24 '18 at 14:33
  • Just parse the json, make the change and stringify it back. I really don't understand why so many people are trying to edit json strings in place. That is not what json is for. – bhspencer May 24 '18 at 14:39
  • So far I've only found functions that can append data to the end of the JSON object which doesn't work for me. The response is just the responsebody that I receive after a request sends in Postman. I use responseBody = JSON.parse(responseBody). – S. Liu May 24 '18 at 14:41
  • In that case your question is nothing to do with json. All you are asking is how do you insert an item at a specific location in a javascript array. https://stackoverflow.com/questions/586182/how-to-insert-an-item-into-an-array-at-a-specific-index – bhspencer May 24 '18 at 14:42

1 Answers1

0

There is nothing like "JSON object" in javascript. You have Javascript objects/arrays, arrays of objects or string containing "Java Script Object Notation".

You can use JSON.stringify() and JSON.parse() to get from one to another.

"decision" in your example will be array after parsing JSON string by JSON.parse(). You can add object into middle of an array using its method splice().

Example:

var jsonstring = '...'; 
var obj = JSON.parse(jsonstring);  
obj.decision.splice(1,0,{ "foo1": "true", "foo2": "false"});  
jsonstring = JSON.stringify($obj);
Petr
  • 1,159
  • 10
  • 20