Add an object to existing json

I want to add an object(key value pair) to a payload that i am getting from the external data file.

“payload”:"{“key1”:“value1”,“key2”:“value2”,“key3”:“value3”}"

What I want to do is add (“key4”:“value4”) to the payload that I use in request body.

payload = {“key1”:“value1”,“key2”:“value2”,“key3”:“value3”}

payload.key4 = value4

how would i use that? I mean lets suppose the payload(from external data file) is put in the body as

{
“branchPayloadDTO”: {{payload}}
}

How would i add another key value pair to that payload in request body?

payload = {“key1”:“value1”,“key2”:“value2”,“key3”:“value3”}

payload.key4 = value4

pm.environment.set("payload",payload)

@praveendvd Don’t you want to stringify it, otherwise it won’t behave as expected? :thinking:

@baljindernohra to add to praveen’s answer…You’d have to update the script like so:

let payload = { "key1": "value1", "key2": "value2", "key3": "value3" };

payload.key4 = value4;

// I'd go with local scope variables to avoid polluting the environment
// but you're free to choose global/environment scoped variables also.
pm.variables.set("payload", JSON.stringify(payload));



Now in your request body (make sure you don’t put quotes (") around the “payload” variable):

{
    "branchPayloadDTO": {{payload}}
}

you don’t have to stringify it if branchPayloadDTO is an object , Stringify and enclose it with bracket only if its need to be send as a string

“payload”:"{“key1”:“value1”,“key2”:“value2”,“key3”:“value3”}"

The payload in question is incorrect as its not escaping the double quotes inside , so can’t say whether the author excepts string or json as payload

Nope, the way the data is stored in the environments (or any variable scope) is in a string format.
So if you don’t stringify it as a JSON before storing it in the env/any variable, then the environment is going to internally call a .toString over the object and it’s going to convert it to something that looks like [object Object]

See the response from the server which shows what kind of data is received.

Without stringification:




After stringification:

Either way, they would want to send an object and the data and not “[object Object]”

1 Like

@singhsivcan you are right body except a string :partying_face: thanks for the correction

1 Like

@praveendvd @singhsivcan Thanks for the quick response guys. I had to stringify it before setting it as a variable.

1 Like