Parse JSON Postman response - json

I have a test in Postman where I do a post request and need to parse the json response
The response looks like this:
"aPIProxy" : [ {
"name" : "SFDC-UpdateLoginTime-v1",
"revision" : [ {
"configuration" : {
"basePath" : "/",
"steps" : [ ]
},
"name" : "1",...some attributes}]
and i need to get something like :
"name" : "SFDC-UpdateLoginTime-v1"
"name" : "1"
for a multiple occurrence json file.

The below postman script might help you.
var jsonData = JSON.parse(responseBody);
var jsonNamesData = jsonData.aPIProxy;
console.log(jsonNamesData);
var parsedData = "";
for(var i=0;i<jsonNamesData.length;i++){
parsedData = parsedData +"\"name\" : \"" +jsonNamesData[i].name+"\", ";
console.log("\"name\" : \"" +jsonNamesData[i].name+"\"");
}
console.log(parsedData);
postman.setEnvironmentVariable("parsedNamesResponse", parsedData); // updating parsed data to the environment variable parsedNamesResponse

You could capture multiple 'name' properties using the _.map() function of Lodash, which is a built it module on the native application. I've had to modify what you need slightly as the name key would have been a duplicate.
const result = _.map(pm.response.json().aPIProxy, data => ({
name: data.name,
revisionName: data.revision[0].name
}))
pm.environment.set("response", JSON.stringify(result))
This would then store all the values in an environment variable for you to use elsewhere in another request.

You should first parse the response using JSON.parse, then you can iterate on the parsed object like:
var resObj = JSON.parse(pm.response.text())
for(var i=0; i< resObj.length; i++) {
console.log("name: "+ resObj[i].name);
}

Related

Add new attribute to JSON

Using Node js and Sequelize ORM, i'm getting a data set. I need to add a new attribute to received data and send it to client side. This is what i tried.
Code Block 1
var varAddOns = { "id" : 5, "Name" : "Cheese"};
global.meal.findOne(
{
where: { id: 5 }
}).then(varMeal => {
var obj = {};
obj = varMeal;
obj.addons = varAddOns;
res.send(obj);
});
It returns a json like below. (Actually it does not contain "addons" data)
Code Block 2
{
"id": 12,
"mealName": "Burger",
"description": "Oily food",
}
but actually what i want is,
Code Block 3
{
"id": 12,
"mealName": "Burger",
"description": "Oily food",
"addons" : {
"id" : 5,
"Name" : "Cheese"
}
}
I tried something like below and it also wont work. (It returns same json as "Code Block 2'.)
Code Block 4
var newJson = {};
newJson = JSON.stringify(varMeal);
newJson['addons'] = varAddOns;
var retVal = JSON.parse(newJson);
res.send(retVal);
Can you help me to figure out, where the issue is?
EDIT
Code Block 5
var newJson = {};
newJson = varMeal;
newJson['addons'] = varAddOn;
var retVal = newJson;// JSON.parse(newJson);
res.send(retVal);
I tried 'Code block 5' as well. Same result comes out as 'Code block 2'. When I use JSON.parse(newJson), it was thrown an error. (Error is Unexpected token o in JSON at position 1)
You need to call .get on your model instance, and then attach extra properties to it:
var varAddOns = { "id" : 5, "Name" : "Cheese"};
global.meal.findOne(
{
where: { id: 5 }
}).then(varMeal => {
var obj = {};
obj = varMeal.get();
obj.addons = varAddOns;
res.send(obj);
});
A few things:
When you call findOne, Sequelize return a model instance, not a plain JS object with your data.
If you want to add extra properties to send to your user, you will first need to convert your model instance to a JS object with your data. You can do this by calling varMeal.get(). From there, you can add extra properties to it.
There is no need to prepend your variables with "var". It would be better to simply name your variable meal
you need the JSON to be an object when you are declaring newJson['addons'] as a nested object
Have you tried (in code block 4) not stringifying varMeal?

NodeJS JSON.parse convert the char ! into?

i have a problem with JSON.parse() in a NodeJS programm usging Express.
The problem is that when i get an external json using http.get for example like this:
[ { "Name" : "Parachutes", "Artist" : "Coldplay"}, { "Name" : "Lost!", "Artist": "Coldplay" } ]
When i do JSON.parse(ResponseStr) the i get the following json
[ { "Name" : "Parachutes", "Artist" : "Coldplay"}, { "Name" : "Lost?", "Artist": "Coldplay" } ]
The char ! is converting into ? when i do that JSON.parse, i want to have the same output as the original Name because when i want to use that name in a http.get('/example.com/album/Lost?') it is returning to me a 404 error.
This is mi my code:
function httpget(url,callback)
{
var str = "";
http.get(url, function(resp){
resp.on('data', function(chunk){
str += chunk;
});
resp.on('end', function(){
var obj = JSON2.parse(str);
callback(obj);
});
});
}
Edit 1:
I already using resp.setEncoding('utf8'); in my code, the problem is in in the JSON2.parse() (is same as JSON.parse()), before that i can do console.log(str) and the output will show "Lost!" but when i do JSON.parse() the output is like this "Lost?"

How to convert a MongoDB document to JSON Object

I am trying to make a post request with the MongoDB document returned from find query, as the request body in NodeJS.But on the server I'm getting the Error : Invalid JSON. Below is the document that I'm trying to POST
{
"_id" : ObjectId("5739a6bf3f1b41477570dc89"),
"taskCount" : 2,
"study" : "cod",
"phase" : "mansa2",
"rhimeTaskId" : "5739a6bec4567f6e737fd3db",
"recordId" : "5726f3cfc4567f6e737fc3ab",
"recordStudy" : "codstudy",
"recordPhase" : "mansa2",
"recordLanguage" : "Punjabi",
"recordScript" : "Latin",
"_state" : "CodingComplete",
"tasks" : [
{
"physician" : ObjectId("5739a6bd3f1b41477570dc78"),
"stage" : "Coding",
"result" : {
"cod" : "C15",
"feedback" : {
"narrativeLength" : "Adequate",
"positiveSymptomsIncluded" : "Only Positive",
"certainty" : "High"
},
"keywords" : [
"52 yr male, died of food pipe cancer, suffered pain upper abdomen, investigated,FNAC confirmed Cancer, Put on Chemotherapy, multiple cycles, died at home, had fever with chills occasionally"
]
}
},
{
"physician" : ObjectId("5739a6bd3f1b41477570dc79"),
"stage" : "Coding",
"result" : {
"cod" : "C15",
"feedback" : {
"narrativeLength" : "Inadequate",
"positiveSymptomsIncluded" : "Only Positive",
"certainty" : "High"
},
"keywords" : [
"severe pain abdomen, ultrasonography revealed food pipe cancer, chemotherapy given, died"
]
}
}
],
"__v" : 2
}
and here is the code that I wrote to make the POST request
var MongoClient = require('mongodb').MongoClient;
var request = require('request');
var assert = require('assert');
var cmeprovisioning= 'mongodb://localhost:27017/cmeprovisioning';
MongoClient.connect(cmeprovisioning, function(err, db) {
assert.equal(null, err);
var count=0;
console.log("Connected to cmeprovisioning");
var cursor =db.collection('rhimeReport').find(
{"study":"cod","phase":"mansa2","recordStudy":"codstudy",
"recordPhase":"mansa2","_state":"CodingComplete"
});
cursor.each(function(err, doc) {
assert.equal(err, null);
if (doc != null) {
console.dir(doc);
count=count+1;
request({url: "http://cme.host.net:8081/cme-provisioning/update",
method: "POST",json: true,
headers: {"content-type": "application/json"},
json: doc
},function(e,r,b){
console.log("POST Error "+count+" "+e)
console.log("POST Response "+count+" "+r)
console.log("POST BODY "+count+" "+b)
});
} else {
console.log("Some Error : "+err)
}
});
});
I also tried using JSON.stringify(doc), but still got the Invalid JSON error. Is there a way I can use mongo document returned by the find query and convert it to JSON to make the POST request.
I think those ObjectID is what making it an invalid JSON document.
Here's the actual answer:
If you want to convert a mongo object to JSON object.
There's a utility method in every mongo object toJSON
So you can simply do mongoResponseObject.toJSON() on the response object.
e.g.
Products.findById(id).then(res => {
const jsonRes = res.toJSON();
// Here jsonRes is JSON
})
Alternatively you can directly get the JSON object by using the .lean() like this.
Products.findById(id).lean().then(res => {
// Here res is JSON
})
you need to convert object id to string ie.
var result = {
"_id": ObjectId("5739a6bf3f1b41477570dc89"),
"taskCount": 2,
"study": "cod"
};
//now convert to string
result=result._id.toString();
//now you can use the result
Try this,
var cursor =db.collection('rhimeReport').find(
{"study":"cod","phase":"mansa2","recordStudy":"codstudy",
"recordPhase":"mansa2","_state":"CodingComplete"});
cursor.toString();
......
Hope this help.
Try this in robomongo
var cursor = db.getCollection('X').find({},{})
while(cursor.hasNext()) {
print(JSON.stringify(cursor.next()))
}

Node JS : Conversion from JSON to CSV

I have a JSON like this,
{
"Name" : "Gokul",
"PhoneNumber" : 9876543210,
"Qualification" : "BE"
}
I need to convert it to CSV and the converted CSV should not have JSON keys, I need to convert only JSON values to CSV and my result should be like this,
["Gokul",9876543210,"BE"]
Using Node JS, I need to this Conversion.
You could install lodash (npm install lodash) and use _.values:
var _ = require('lodash');
var json = { "Name" : "Gokul", "PhoneNumber" : 9876543210, "Qualification" : "BE" };
var values = _.values(json); // It will be ["Gokul",9876543210,"BE"]
var json = { "Name" : "Gokul", "PhoneNumber" : 9876543210, "Qualification" : "BE" };
var arr = Object.keys(json).map(function(key,index) {
return json[key];
});
console.log(arr);
//logs [Gokul,9876543210,BE]
console.log(arr.join(','))
//logs Gokul,9876543210,BE

What are standard ways to show that your functions are connected to a certain JSON data structure?

I've a JSON file with a structure that is not yet set; it may grow complex.
I want to keep track of what the functions think the data structure is.
What are standard/smart ways to show that your functions is connected to a certain data structure?
Right now, I'm using a _comment in the json file to keep a version number, and then keeping that version name as a comment in each function that uses it. Full example below.
travel.json
{
"_comment" : "version 1.0"
, "name" : "Tom Sawyer"
, "travel" : [{
"id" : "1"
, "location" : "San Francisco"
}, {
"id" : "2"
, "location" : "London"
}]
}
Two functions to parse: travel.json
fs = require('fs');
function get_json() {
var file = __dirname + '/travel.json';
data = fs.readFileSync(file, 'utf8');
var json_obj = JSON.parse(data);
return(json_obj);
};
function get_location(json_obj) {
// "version 1.0"
var new_obj = {};
json_obj.content.forEach(function(item) {
new_obj[item.id] = item.location;
});
return ( new_obj );
};
// Run
console.log('Locations: ', get_location( get_json() ));
Thanks.
It looks a bit like defensive programming. If you are creating an API that other people will depend on you could version the url of the API instead of the JSON. Something like yoururl/api/1/locations, yoururl/api/2/locations, etc