sofia365
(sofia365)
January 5, 2023, 8:07pm
1
I need to modify json file and not sure how to do it.
First, I send GET request that returns JSON:
{
"id": 100,
"info": {
"type": "abc",
"product": null
}
}
…and I save it into var:
var responseData = pm.response.json();
pm.environment.set("body", responseData);
Next, I need to send PUT request with updated json file. If product=null it will look like :
{
"id": 100,
"info":
"type": "abc",
"product": {
"productId": 123,
"info": {
"available": true,
"restock": {
"enabled": true
}
}
}
}
In my pre-request script I have the following:
var requestBody = pm.environment.get("body");
if (requestBody.info.product !==null) {
requestBody.info.product =null
} else {
jsonObject = JSON.parse(requestBody);
jsonObject.product.push({"productId":"123"});
// I am not sure how to add the rest...
pm.environment.set("updatedBody", JSON.stringify(requestBody));
When I run it I am getting the error: JSONError: Unexpected token ‘o’ at 1:2 [object Object] ^
You have to stringify the responseData before saving it to the “body” environment variable. (Like you do for the updatedBody).
Then parse it when you retrieve it.
You can parse this in one line.
let variableName = JSON.parse(pm.environment.get("body"));
If you use let or var instead of const, then you can update the elements directly.
You don’t really need to use push.
PS: This is a JavaScript object at this point.
In your example, the product.push is incorrect, as surely it should be jsonObject.info.product.
Not sure if its will a valid object after this. (Hence the error).
You can also just define the whole product element, and update it in one go. Like following.
let response = pm.response.json().data; // parse JSON response into JavaScript object.
console.log(response); // original response.
// define product element to replace null entries
const productNull = {
"productId": 123,
"info": {
"available": true,
"restock": {
"enabled": true
}
}
}
if (response.info.product ==null) {
response.info.product = productNull // update response
}
console.log(response) // updated response - remember to stringify before saving to environment\collection variable.
perezben
(Benjamin)
January 9, 2023, 5:37pm
3
Thank you @michaelderekjones , I’ll check this
have a nice day