How to access json nested objects in node.js - json

I have used xml2js parser to parse the xml file in node.js. It is parsing the xml successfully. But now i want to parse the json or to identify the particular data in json.
My node.js code
var fs = require('fs');
var parseString = require('xml2js').parseString;
var xml = 'C:\\temp\\Masters.xml';
var fileData = fs.readFileSync(xml,'utf8');
parseString(fileData, function (err, result) {
console.log(JSON.stringify(result));
var json = JSON.stringify(result);
var jsonObj = JSON.parse(json);
for (var key in jsonObj) {
console.dir(key + ": " + jsonObj[key].Customer_Name);
}
});
In console output:
'Masters: undefined'
Json data:
'{"Masters":
{
"Customer":
[
{"Customer_Name":["Kim"],
"Customer_Code":["c86"],
"Date":["23-11-15"],
"Address":["Narhe"],
"City":["Pune"],
"State":["Maharashtra"],
"TIN":["3365670"],
"PAN_Number":["AAAAA1111a"],
"Mobile_Number":["8999000090"],
"Email_ID":["amitshirke#gmail.com"],
"Contact_Person":["Anish"],
"Opening_Balance":["0"] },
{"Customer_Name":["Ankit"],
"Customer_Code":["c87"],
"Date":["12-04-15"],
"Address":["Narhe"],
"City":["Pune"],
"State":["Maharashtra"],
"TIN":["336567"],
"PAN_Number":["AAAAA1111p"],
"Mobile_Number":["8900000000"],
"Email_ID":["amitshirke1#gmail.com"],
"Contact_Person":["Anuj"],
"Opening_Balance":["0"] }
]
}
}'
In above data, Masters is root element(Object), Customer is another nested object and there two customers. Then how can I access the customer names or how to use the for loop to access the same?.
Thanks in advance.

You can access the Customer array as follows -
var customerArray = Masters.Customer,
length = customerArray.length;
for(var i = 0; i < length; i++)
{
// You can access the customers array from here -
console.log(customerArray[i].Customer_Name[0]); // [0] hardcoded because as you can see all the variables are in array at 0th position
// similarly you can access other data
console.log(customerArray[i].City[0]);
}

Related

Converting Postman Json body request to Jmeter body request

var moment = require("moment");
var time = moment().valueOf();
pm.environment.set('time', time);
var eventArray = [];_
for(var i = 1; i <= 50; i++)
{
var t = time + (i * 1000);
eventArray.push({
"eid": i,
"time": t
});
}
var data = { "event": eventArray };
var JSONData = new Buffer(JSON.stringify(data)).toString();
pm.environment.set("JSONData", JSONData);
console.log("JSONDATA", JSONData);
Change your entire request body to the following variable:
{{JSONData}}
This is what would be sent:
{“event”:[{“eid”:1,“time”:1538518294839},{“eid”:2,“time”:1538518295839},{“eid”:3,“time”:1538518296839},{“eid”:4,“time”:1538518297839},{“eid”:5,“time”:1538518298839},{“eid”:6,“time”:1538518299839},{“eid”:7,“time”:1538518300839},{“eid”:8,“time”:1538518301839},{“eid”:9,“time”:1538518302839},{“eid”:10,“time”:1538518303839},{“eid”:11,“time”:1538518304839},{“eid”:12,“time”:1538518305839},{“eid”:13,“time”:1538518306839},{“eid”:14,“time”:1538518307839},{“eid”:15,“time”:1538518308839},{“eid”:16,“time”:1538518309839},{“eid”:17,“time”:1538518310839},{“eid”:18,“time”:1538518311839},{“eid”:19,“time”:1538518312839},{“eid”:20,“time”:1538518313839},{“eid”:21,“time”:1538518314839},{“eid”:22,“time”:1538518315839},{“eid”:23,“time”:1538518316839},{“eid”:24,“time”:1538518317839},{“eid”:25,“time”:1538518318839},{“eid”:26,“time”:1538518319839},{“eid”:27,“time”:1538518320839},{“eid”:28,“time”:1538518321839},{“eid”:29,“time”:1538518322839},{“eid”:30,“time”:1538518323839},{“eid”:31,“time”:1538518324839},{“eid”:32,“time”:1538518325839},{“eid”:33,“time”:1538518326839},{“eid”:34,“time”:1538518327839},{“eid”:35,“time”:1538518328839},{“eid”:36,“time”:1538518329839},{“eid”:37,“time”:1538518330839},{“eid”:38,“time”:1538518331839},{“eid”:39,“time”:1538518332839},{“eid”:40,“time”:1538518333839},{“eid”:41,“time”:1538518334839},{“eid”:42,“time”:1538518335839},{“eid”:43,“time”:1538518336839},{“eid”:44,“time”:1538518337839},{“eid”:45,“time”:1538518338839},{“eid”:46,“time”:1538518339839},{“eid”:47,“time”:1538518340839},{“eid”:48,“time”:1538518341839},{“eid”:49,“time”:1538518342839},{“eid”:50,“time”:1538518343839}]}
Now i need the above request to be converted as jmeter request and pass in a single variable.
The equivalent Groovy code for using in a suitable JSR223 Test Element would be something like:
def events = []
def time = System.currentTimeMillis()
1.upto(50, {
events.add([eid: it, time: time + it * 1000])
})
def JSONData = new groovy.json.JsonBuilder([event: events]).toPrettyString()
vars.put('JSONData', JSONData)
The generated value can be accessed as ${JSONData} JMeter Variable where required
More information:
Apache Groovy - Parsing and producing JSON
Apache Groovy - Why and How You Should Use It

Convert a javascript array to specific json format

I have this JSON.stringify(array) result: ["id:1x,price:150","id:2x,price:200"] and I have to convert it in a json format similar to this (it would be sent to php):
[{
"id":"1x",
"price":150
},
{
"id":"2x",
"price":200
}]
Please help.
You can convert the structure of your data before using JSON.stringify, for example you can convert the data to a list of objects like so:
var strItems = ["id:1x,price:150", "id:2x,price:200"];
var objItems = [];
for (var i = 0; i < strItems.length; i++) {
var pairs = strItems[i].split(",");
objItems.push({
id: pairs[0].split(':')[1],
price: parseInt(pairs[1].split(':')[1])
});
}
Before calling JSON.stringify to get the result you're after:
var json = JSON.stringify(objItems);
console.log(json);
JSON.stringify(array) only does on layer, but you can change the stringify function to work for multiple layers with this function written by JVE999 on this post:
(function(){
// Convert array to object
var convArrToObj = function(array){
var thisEleObj = new Object();
if(typeof array == "object"){
for(var i in array){
var thisEle = convArrToObj(array[i]);
thisEleObj[i] = thisEle;
}
}else {
thisEleObj = array;
}
return thisEleObj;
};
var oldJSONStringify = JSON.stringify;
JSON.stringify = function(input){
if(oldJSONStringify(input) == '[]')
return oldJSONStringify(convArrToObj(input));
else
return oldJSONStringify(input);
};
})();
Once you have declared this, then you can call JSON.stringify(array)

Store User Control JSON object in DB

I have a JSON object that I want to store in a database. The JSON is generated by an User Control.
The JSON object:
var datatosend = {
isit: isitArray,
ec: ecArray,
bc: bcArray,
bb: bbArray,
io: ioArray
};
What is the best way to record a JSON object in the database using GeneXus?
Edit:
var isitArray = getObjectsRequest('isit', isitID);
var ecArray = getObjectsRequest('ec', ecID);
var bcArray = getObjectsRequest('bc', bcID);
var bbArray = getObjectsRequest('bb', bbID);
var ioArray = getObjectsRequest('io', ioID);
function getObjectsRequest(type, compId){
var array = [];
for (var i = 0; i<compId; i++) {
var comp = mainLayer.find('#'+ type + i)[0];
array.push({
xposition: comp.getX(),
yposition: comp.getY(),
titleid: comp.getId(),
description: comp.find('.textDescription')[0].getText(),
leftrelationsids: comp.leftCRelations,
rightrelationsids: comp.rightCRelations
});
};
return array;
}
var datatosend = {
isit: isitArray,
ec: ecArray,
bc: bcArray,
bb: bbArray,
io: ioArray
};
You can use a LongVarChar attribute to store the JSON, but you'll need to convert the JavaScript object to String first.

How to access name of key in dynamically created json in action script 3

I have a json object coming from my java code as string :
{
"ABC":["ABC","XYZ","pqr"],
"OMG":["ABC","XYZ","pqr"],
"Hello":["ABC","XYZ","pqr"]
}
on decoding it as
myObj : Object = JSON.decode(result);
Now how do I access key names like ABC, OMG, HELLO...??
Try this will help you.
When you want properties in object use for-in loop or you want value use foreach statement.
var obj:Object = {
"ABC":["ABC","XYZ","pqr"],
"OMG":["ABC","XYZ","pqr"],
"Hello":["ABC","XYZ","pqr"]
};
var jsonText:String = JSON.stringify(obj);
var jsonObj:Object = JSON.parse(jsonText);
for(var key:String in jsonObj){
Alert.show("Key is"+key + " value is "+ jsonObj[key]);
}
Your case exactly
var myObj:Object = JSON.decode(result);
for(var key:String in myObj){
Alert.show("Key is"+key + " value is "+ myObj[key]);
}

Parsing json jquery

My request ajax with json_encode:
[{"idHome":"1","Photo":"home-1.jpg","Publier":"1"},
{"idHome":"2","Photo":"home2.jpg","Publier":"1"},
{"idHome":"3","Photo":"home3.jpg","Publier":"1"}]
var string = JSON.stringify(data);
var obj = $.parseJSON(string);
console.log(string);
var idHome = obj.idHome;
var photo = obj.Photo;
console.log(obj.idHome);
console.log(obj.Photo);
Problem with parsing json
console log :
[{"idHome":"1","Photo":"home-1.jpg","Publier":"1"},{"idHome":"2","Photo":"home-2.jpg","Publier":"1"},{"idHome":"3","Photo":"home-3.jpg","Publier":"1"}]
undefined
undefined
It is an array so you need to loop through, there are so many ways to do it.
for (i = 0; i < obj.length; i++) {
console.log(obj[i].idHome);
console.log(obj[i].Photo);
}
or:
obj.forEach(function(val) {
console.log(val.idHome);
console.log(val.Photo);
});
or:
for (var i in obj) {
console.log(obj[i].idHome);
console.log(obj[i].Photo);
}
Jquery use :
$.each(obj, function(_, val){
console.log(val.idHome);
console.log(val.Photo);
});
and so on....
Your json is an array of three objects.
Try
console.log(obj[0].idHome);
console.log(obj[0].Photo);
More info:
http://www.w3schools.com/json/json_syntax.asp