Home > OS >  Convert Text Response into JSON array (Postman)
Convert Text Response into JSON array (Postman)

Time:12-15

I'm trying to convert a Text Response I am getting in POSTMAN into a JSON array and looking for any help. Right now, I can create variables from a Text Response by using .split() it like so:

Response:

1. 1c522d76-5d20-11ec-bf63-0242ac130002↵
2. 1c522fc4-5d20-11ec-bf63-0242ac130002↵
3. 1c5230d2-5d20-11ec-bf63-0242ac130002↵
4. 1c5231c2-5d20-11ec-bf63-0242ac130002↵
5. 1c5232a8-5d20-11ec-bf63-0242ac130002↵

Setting Collection Variables by splitting the Text Response (Each UUID is a variable)

pm.collectionVariables.set("UUID_1", res.text().split("\r\n")[0])   
pm.collectionVariables.set("UUID_2", res.text().split("\r\n")[1])
pm.collectionVariables.set("UUID_3", res.text().split("\r\n")[2])
pm.collectionVariables.set("UUID_4", res.text().split("\r\n")[3])
pm.collectionVariables.set("UUID_5", res.text().split("\r\n")[4])

However, instead of creating variables this way, I think a better idea is to convert the text response into a JSON Array. This way I would be able to work towards my goal of Looping API Requests until the JSON Array is complete.

So far, I have this: Which is setting a env variable by stringifying it ,which is pretty much creating a string but I think its stringing the whole Text Response into one String.

let body = pm.response.text()
pm.environment.set('text2json', JSON.stringify(body));
console.log(body)

which you'll notice how it puts its in double quotes:

""1c522d76-5d20-11ec-bf63-0242ac130002\r\n1c522fc4-5d20-11ec-bf63-0242ac130002\r\n1c5230d2-5d20-11ec-bf63-0242ac130002\r\n1c5231c2-5d20-11ec-bf63-0242ac130002\r\n1c5232a8-5d20-11ec-bf63-0242ac130002""

And unfortunately getting an error if I try get the Env Variable and console log it like so:

console.log(pm.environment.get("text2json"))

Error:

JSONError: Unexpected token 'c' at 1:21c522d76-5d20-11ec-bf63-0242ac130002

Looking for a way to make this work and get it into a JSON Array.

CodePudding user response:

Just JSON.stringify after split, then it solves your problem.

let body = pm.response.text()
pm.environment.set('text2json', JSON.stringify(body.split("\r\n")));
console.log(body)

CodePudding user response:

let response = pm.response.text().split('\n'), jsonObject = {}
response.forEach((item,index)=>{
    jsonObject[`uuid_${index}`] = item
})

console.log(jsonObject)

just add it in an array and iterate through each element and add it to an object

  • Related