How to convert array of object to XML format? - javascript

Hi I am working on node project. I got a requirement like i have array of object data, i have to convert that to xml format. i tried with json2xml libray. i converted but it is created only single Agent Tag.
In side the agents tag i need separate agent including refURL for each agent tag
each agent Tag should have refurl,agentID,firstName,lastName, userName agent, but the converted xml is combining all refurl,agentID,firstName,lastName, userName is single agent tag
{
"refURL": "/unifiedconfig/config/agentteam/5022",
"changeStamp": 12,
"agentCount": 7,
"description": "Cumulus Outbound Team",
"name": "CumulusOutbound",
"peripheral": {
"id": 5000,
"name": "CUCM_PG_1"
},
"peripheralId": 5000,
"supervisorCount": 1,
"agents": [{
"agent": [{
"refURL": "/unifiedconfig/config/agent/5197",
"agentId": "1085",
"firstName": "Owen",
"lastName": "Harvey",
"userName": "oharvey"
}, {
"refURL": "/unifiedconfig/config/agent/5201",
"agentId": "1320",
"firstName": "Bruce",
"lastName": "Wayne",
"userName": "bwayne"
}, {
"refURL": "/unifiedconfig/config/agent/5202",
"agentId": "1321",
"firstName": "Peter",
"lastName": "Parker",
"userName": "pparker"
}, {
"refURL": "/unifiedconfig/config/agent/5203",
"agentId": "1322",
"firstName": "Tony",
"lastName": "Stark",
"userName": "tstark"
}, {
"refURL": "/unifiedconfig/config/agent/5204",
"agentId": "1323",
"firstName": "Steve",
"lastName": "Rogers",
"userName": "srogers"
}, {
"refURL": "/unifiedconfig/config/agent/5205",
"agentId": "1324",
"firstName": "Bruce",
"lastName": "Banner",
"userName": "bbanner"
}, {
"refURL": "/unifiedconfig/config/agent/5231",
"agentId": "1086",
"firstName": "Annika",
"lastName": "Hamilton",
"userName": "annika"
}, {
"refURL": "/unifiedconfig/config/agent/5118",
"agentId": "1317",
"firstName": "Donald",
"lastName": "Duckling",
"userName": "dduck"
}]
}],
"supervisors": [{
"supervisor": [{
"refURL": "/unifiedconfig/config/agent/5174",
"agentId": "1082",
"firstName": "Rick",
"lastName": "Barrows",
"userName": "rbarrows#dcloud.cisco.com"
}]
}]
}
Actually it should be like below
<agentTeam>
<refURL>/unifiedconfig/config/agentteam/5022</refURL>
<changeStamp>12</changeStamp>
<agentCount>7</agentCount>
<description>Cumulus Outbound Team</description>
<name>CumulusOutbound</name>
<peripheral>
<id>5000</id>
<name>CUCM_PG_1</name>
</peripheral>
<peripheralId>5000</peripheralId>
<supervisorCount>1</supervisorCount>
<agents>
<agent>
<refURL>/unifiedconfig/config/agent/5197</refURL>
<agentId>1085</agentId>
<firstName>Owen</firstName>
<lastName>Harvey</lastName>
<userName>oharvey</userName>
</agent>
<agent>
<refURL>/unifiedconfig/config/agent/5201</refURL>
<agentId>1320</agentId>
<firstName>Bruce</firstName>
<lastName>Wayne</lastName>
<userName>bwayne</userName>
</agent>
<agent>
<refURL>/unifiedconfig/config/agent/5202</refURL>
<agentId>1321</agentId>
<firstName>Peter</firstName>
<lastName>Parker</lastName>
<userName>pparker</userName>
</agent>
<agent>
<refURL>/unifiedconfig/config/agent/5203</refURL>
<agentId>1322</agentId>
<firstName>Tony</firstName>
<lastName>Stark</lastName>
<userName>tstark</userName>
</agent>
<agent>
<refURL>/unifiedconfig/config/agent/5204</refURL>
<agentId>1323</agentId>
<firstName>Steve</firstName>
<lastName>Rogers</lastName>
<userName>srogers</userName>
</agent>
<agent>
<refURL>/unifiedconfig/config/agent/5205</refURL>
<agentId>1324</agentId>
<firstName>Bruce</firstName>
<lastName>Banner</lastName>
<userName>bbanner</userName>
</agent>
<agent>
<refURL>/unifiedconfig/config/agent/5231</refURL>
<agentId>1086</agentId>
<firstName>Annika</firstName>
<lastName>Hamilton</lastName>
<userName>annika</userName>
</agent>
</agents>
<supervisors>
<supervisor>
<refURL>/unifiedconfig/config/agent/5174</refURL>
<agentId>1082</agentId>
<firstName>Rick</firstName>
<lastName>Barrows</lastName>
<userName>rbarrows#dcloud.cisco.com</userName>
</supervisor>
</supervisors>
</agentTeam>
But it is converted like below
<agentTeam>
<refURL>/unifiedconfig/config/agentteam/5018</refURL>
<changeStamp>9</changeStamp>
<agentCount>4</agentCount>
<description>Cumulus City Team</description>
<name>CumulusCity</name>
<peripheral>
<id>5000</id>
<name>CUCM_PG_1</name>
</peripheral>
<peripheralId>5000</peripheralId>
<supervisorCount>1</supervisorCount>
<agents>
<agent>
<refURL>/unifiedconfig/config/agent/5113</refURL>
<agentId>1312</agentId>
<firstName>John</firstName>
<lastName>Elway</lastName>
<userName>jelway</userName>
<refURL>/unifiedconfig/config/agent/5118</refURL>
<agentId>1317</agentId>
<firstName>Donald</firstName>
<lastName>Duck</lastName>
<userName>dduck</userName>
<refURL>/unifiedconfig/config/agent/5119</refURL>
<agentId>1318</agentId>
<firstName>Elmer</firstName>
<lastName>Fudd</lastName>
<userName>efudd</userName>
</agent>
</agents>
<supervisors>
<supervisor>
<refURL>/unifiedconfig/config/agent/5174</refURL>
<agentId>1082</agentId>
<firstName>Rick</firstName>
<lastName>Barrows</lastName>
<userName>rbarrows#dcloud.cisco.com</userName>
</supervisor>
</supervisors>
</agentTeam>

Transform the json before conversion
As noted in comments, the problem is with the json schema. Specifically the agent property is an array of one item whereas it should be an array of agents. If you can't fix this problem at the json source then you will need to transform the data before feeding it to the json2xml converter.
And I think this can be done with a simple Array.map like so:
data.agents = data.agents[0].agent.map(agent => ({agent: agent}));
Update
In response to OP's comment, the snippet was updated to display all the data rather than only what was changed.
Snippet
Run the snippet to see the result.
const data = {"refURL":"/unifiedconfig/config/agentteam/5022","changeStamp":12,"agentCount":7,"description":"Cumulus Outbound Team","name":"CumulusOutbound","peripheral":{"id":5000,"name":"CUCM_PG_1"},"peripheralId":5000,"supervisorCount":1,"agents":[{"agent":[{"refURL":"/unifiedconfig/config/agent/5197","agentId":"1085","firstName":"Owen","lastName":"Harvey","userName":"oharvey"},{"refURL":"/unifiedconfig/config/agent/5201","agentId":"1320","firstName":"Bruce","lastName":"Wayne","userName":"bwayne"},{"refURL":"/unifiedconfig/config/agent/5202","agentId":"1321","firstName":"Peter","lastName":"Parker","userName":"pparker"},{"refURL":"/unifiedconfig/config/agent/5203","agentId":"1322","firstName":"Tony","lastName":"Stark","userName":"tstark"},{"refURL":"/unifiedconfig/config/agent/5204","agentId":"1323","firstName":"Steve","lastName":"Rogers","userName":"srogers"},{"refURL":"/unifiedconfig/config/agent/5205","agentId":"1324","firstName":"Bruce","lastName":"Banner","userName":"bbanner"},{"refURL":"/unifiedconfig/config/agent/5231","agentId":"1086","firstName":"Annika","lastName":"Hamilton","userName":"annika"},{"refURL":"/unifiedconfig/config/agent/5118","agentId":"1317","firstName":"Donald","lastName":"Duckling","userName":"dduck"}]}],"supervisors":[{"supervisor":[{"refURL":"/unifiedconfig/config/agent/5174","agentId":"1082","firstName":"Rick","lastName":"Barrows","userName":"rbarrows#dcloud.cisco.com"}]}]}
before.innerHTML = JSON.stringify(data, null, " ");
data.agents = data.agents[0].agent.map(agent => ({agent: agent}));
after.innerHTML = JSON.stringify(data,null," ");
body {
font-family: sans-serif;
}
.container {
display: flex;
}
.card {
margin: 0.5rem;
padding: 0.5rem;
border: 1px solid gray;
overflow: hidden;
}
textarea {
padding: 0.5rem;
width: 100%;
height: 10rem;
}
<div class="container">
<div class="card">
<div>Original Data:</div>
<pre id="before"></pre>
</div>
<div class="card">
<div>Transformed Data:</div>
<pre id="after"></pre>
</div>
</div>

Related

how to add number to field in every document in mongodb using nodejs

My collection has a phonenumber field. I want to add 91 in front of phonenumber.
{
"_id": "6137392141bbb7723",
"email": "brooke#cagle.com",
"lastname": "Cagle",
"firstname": "Brooke",
"phonenumber":9000000001
},
{
"_id": "6137392141bbe30723",
"email": "brooke#cagle.com",
"lastname": "Cagle",
"firstname": "Brooke",
"phonenumber":9000000002
}
I want to update my collection like this.
{
"_id": "6137392141bbb7723",
"email": "brooke#cagle.com",
"lastname": "Cagle",
"firstname": "Brooke",
"phonenumber":919000000001
},
{
"_id": "6137392141bbe30723",
"email": "brooke#cagle.com",
"lastname": "Cagle",
"firstname": "Brooke",
"phonenumber":919000000002
}
I'm trying with this code but it's not updating the field.
var x = await User.find({});
x.forEach(async function(d)
{
var phone = d.phonenumber;
var newPhoneNumber = 910000000000+phone;
console.log(newPhoneNumber);
//update
await User.updateMany({},{$set:{phonenumber:newPhoneNumber}},
{
new: true,
runValidators : true
});
})
I'm getting only one value for all documents like this:
{
"_id": "6137392141bbb7723",
"email": "brooke#cagle.com",
"lastname": "Cagle",
"firstname": "Brooke",
"phonenumber":919000000001
},
{
"_id": "6137392141bbe30723",
"email": "brooke#cagle.com",
"lastname": "Cagle",
"firstname": "Brooke",
"phonenumber":919000000001
},
{
"_id": "6137392141bbe30723",
"email": "brooke#cagle.com",
"lastname": "Cagle",
"firstname": "Brooke",
"phonenumber":919000000001
}
I don't know whether this approach is correct or not.
I have found a solution. Maybe, this works,
let mobile = 9876543210;
let phone = `91${mobile}`;
let final = Number(phone)
console.log(typeof(final), final+3);
So,
var phone = d.phonenumber;
var newPhoneNumber = Number(`91${phone}`);
console.log(newPhoneNumber);
Read more about Number() : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number
Playground
db.collection.update({},
//To match all documents
[{
$set: {
key: {
$toInt: {
$concat: [
"91",
{
$toString: "$key"
}
]
}
}
}
}
],
//Concatenate 91 and the value in the field
{multi: true
})
This is applicable for mongo versions from 4.2. This is aggregation pipeline which is used in update query.
Reference
EDIT:
You would have got overFlow error. You could use toLong in this case.
db.mybooks.update({},
//To match all documents
[{
$set: {
key: {
$toLong: {
$concat: [
"91",
{
$toString: "$key"
}
]
}
}
}
}
],
//Concatenate 91 and the value in the field
{multi: true
})
It's tested piece of code.

How to JSON.stringify multiple objects returned from Loop

Here is my mvc code, I want to add multiple travelers objects to travelers array which are generated in a loop and then JSON.stringify them,
return amadeus.booking.flightOrders.post(
JSON.stringify({
'data':{
'type': 'flight-order',
'flightOffers': [response.data.flightOffers[0]],
'travelers':[{
"id": 1,
"name": {
"firstName": req.body.firstname,
"lastName": req.body.lastname
},
"gender": req.body.gender,
"contact": {
"emailAddress": req.body.emailaddress,
"phones": [{
"deviceType": req.body.devicetype,
"countryCallingCode": req.body.countrycallingcode,
"number": req.body.number
}]
},
"documents": [{
"documentType": req.body.documentype,
"birthPlace": req.body.birthplace,
"issuanceLocation": req.body.issuancelocation,
"issuanceDate": req.body.issuancedate,
"number": req.body.p_number,
"expiryDate": req.body.expirydate,
"issuanceCountry": req.body.issuancecountry,
"validityCountry": req.body.validitycountry,
"nationality": req.body.nationality,
"holder": true
}]
}]
}
})
);
I there a simple way to achieve that?
JSON.stringify converts a JS object to a string. It does not control or require any specifications for the object's structure in general.
In your case, you can simply add multiple data objects to your travelers' array e.g
return amadeus.booking.flightOrders.post(
JSON.stringify({
'data':{
'type': 'flight-order',
'flightOffers': [response.data.flightOffers[0]],
'travelers':[{
"id": 1,
"name": {
"firstName": req.body.firstname,
"lastName": req.body.lastname
},
"gender": req.body.gender,
"contact": {
"emailAddress": req.body.emailaddress,
"phones": [{
"deviceType": req.body.devicetype,
"countryCallingCode": req.body.countrycallingcode,
"number": req.body.number
}]
},
"documents": [{
"documentType": req.body.documentype,
"birthPlace": req.body.birthplace,
"issuanceLocation": req.body.issuancelocation,
"issuanceDate": req.body.issuancedate,
"number": req.body.p_number,
"expiryDate": req.body.expirydate,
"issuanceCountry": req.body.issuancecountry,
"validityCountry": req.body.validitycountry,
"nationality": req.body.nationality,
"holder": true
}]
},{
"id": 2,
"name": {
"firstName": req.body.firstname,
"lastName": req.body.lastname
},
"gender": req.body.gender,
"contact": {
"emailAddress": req.body.emailaddress,
"phones": [{
"deviceType": req.body.devicetype,
"countryCallingCode": req.body.countrycallingcode,
"number": req.body.number
}]
},
"documents": [{
"documentType": req.body.documentype,
"birthPlace": req.body.birthplace,
"issuanceLocation": req.body.issuancelocation,
"issuanceDate": req.body.issuancedate,
"number": req.body.p_number,
"expiryDate": req.body.expirydate,
"issuanceCountry": req.body.issuancecountry,
"validityCountry": req.body.validitycountry,
"nationality": req.body.nationality,
"holder": true
}]
},{
"id": 3,
.
.
.
},{
"id": 4,
.
.
.
}]
}
})
);
and JSON.stringify will convert whole object to string.
To loop on data and add the travelers array, one approach will be:
const travelers = [];
for(let i=0;i<10;i++){
travelers.push({});
}
and then
return amadeus.booking.flightOrders.post(
JSON.stringify({
'data':{
'type': 'flight-order',
'flightOffers': [response.data.flightOffers[0]],
'travelers': travelers
}
})
);

access elements in an array of objects [duplicate]

This question already has answers here:
From an array of objects, extract value of a property as array
(24 answers)
Closed 3 years ago.
I Want to separate the elements from an array of objects in to another array
emplist = [
{
"empid": "CL4NX1569868029",
"orgid": "ZARQP1569826662",
"accid": "95057056798",
"fstname": "Testname",
"lastname": "Last",
"email": "test.mk#gmail.com"
},
{
"empid": "HMXEN1569860677",
"orgid": "ZARQP1569826662",
"accid": "9505705709",
"fstname": "Testname1",
"lastname": "Last",
"email": "test.mk#gmail.com"
},
{
"empid": "UX74A1569908006",
"orgid": "ZARQP1569826662",
"accid": "9100",
"fstname": "abc",
"lastname": "abc",
"email": "abc#abc.com"
},
]
I want to separate fstname and lastname like
source = [ "Testname Last" , "Testname1 Last" , "abc abc" ]
You can simply use map to transform the emplist array into another array with first and last names concatenated (here I used template literal, but you can just use +).
const emplist = [
{
"empid": "CL4NX1569868029",
"orgid": "ZARQP1569826662",
"accid": "95057056798",
"fstname": "Testname",
"lastname": "Last",
"email": "test.mk#gmail.com"
},
{
"empid": "HMXEN1569860677",
"orgid": "ZARQP1569826662",
"accid": "9505705709",
"fstname": "Testname1",
"lastname": "Last",
"email": "test.mk#gmail.com"
},
{
"empid": "UX74A1569908006",
"orgid": "ZARQP1569826662",
"accid": "9100",
"fstname": "abc",
"lastname": "abc",
"email": "abc#abc.com"
},
];
const source = emplist.map((emp) => `${emp.fstname} ${emp.lastname}`);
console.log(source);

JSON Response Parsing Error - Javascript

I have the following JSON response coming from an API.
{
"status": true,
"cakes": {
"7689": {
"id": 7689,
"flavor": "chocolate",
"cookDetails": {
"id": 101,
"firstName": "Name1",
"lastName": "LastName1"
}
},
"7690": {
"id": 7690,
"flavor": "vanilla",
"cookDetails": {
"id": 102,
"firstName": "Name2",
"lastName": "LastName2"
}
}
}
}
Language I'm using to parse this JSON: Javascript
Framework: ReactNative
My question is:
1. Is the JSON format correct?
2. If yes, then how do I parse it (NOTE: I don't know the value of id in cakes until I parse it)?
PS: New to the framework. Big thanks.
Try using this,
{
"status": true,
"cakes": [{
"id": 7689,
"flavor": "chocolate",
"cookDetails": {
"id": 101,
"firstName": "Name1",
"lastName": "LastName1"
}
}, {
"id": 7690,
"flavor": "vanilla",
"cookDetails": {
"id": 102,
"firstName": "Name2",
"lastName": "LastName2"
}
}]
}
for ReactNative check this :https://facebook.github.io/react-native/docs/network.html
http://www.9lessons.info/2017/04/react-native-json-parsing-and-helper.html
Note below code HTML JavaScript for your understanding.
var obj = JSON.parse('{"status": true,"cakes": [{"id": 7689,"flavor": "chocolate","cookDetails": {"id": 101,"firstName": "Name1","lastName": "LastName1"}},{"id": 7690,"flavor": "vanilla","cookDetails": {"id": 102,"firstName": "Name2","lastName": "LastName2"}}]}');
<!DOCTYPE html>
<html>
<body>
<h2>Create Object from JSON String</h2>
<p id="demo"></p>
<script>
var obj = JSON.parse('{"status": true,"cakes": [{"id": 7689,"flavor": "chocolate","cookDetails": {"id": 101,"firstName": "Name1","lastName": "LastName1"}},{"id": 7690,"flavor": "vanilla","cookDetails": {"id": 102,"firstName": "Name2","lastName": "LastName2"}}]}');
document.getElementById("demo").innerHTML = obj.cakes[0].id +", "+ obj.cakes[0].flavor+", "+obj.cakes[0].cookDetails.id+", "+obj.cakes[0].cookDetails.firstName+", "+obj.cakes[0].cookDetails.lastName;
</script>
</body>
</html>
Here is valid JSON(just extra commas were removed):
{
"status": true,
"cakes": {
"7689": {
"id": 7689,
"flavor": "chocolate",
"cookDetails": {
"id": 101,
"firstName": "Name1",
"lastName": "LastName1"
}
},
"7690": {
"id": 7690,
"flavor": "vanilla",
"cookDetails": {
"id": 102,
"firstName": "Name2",
"lastName": "LastName2"
}
}
}
}
You can parse it with plain JSON.parse call

Convert json to a string using jquery

I have a nested json. I want to post it as a form input value.
But, seems like jquery puts "Object object" string into the value.
It seems easier to pass around the string and convert into the native form I need, than dealing with json as I don't need to change anything once it is generated.
What is the simplest way to convert a json
var json = {
"firstName": "John",
"lastName": "Smith",
"age": 25,
"address": {
"streetAddress": "21 2nd Street",
"city": "New York",
"state": "NY",
"postalCode": "10021"
},
"phoneNumber": [
{ "type": "home", "number": "212 555-1234" },
{ "type": "fax", "number": "646 555-4567" }
],
"newSubscription": false,
"companyName": null
};
into its string form?
var json = '{
"firstName": "John",
"lastName": "Smith",
"age": 25,
"address": {
"streetAddress": "21 2nd Street",
"city": "New York",
"state": "NY",
"postalCode": "10021"
},
"phoneNumber": [
{ "type": "home", "number": "212 555-1234" },
{ "type": "fax", "number": "646 555-4567" }
],
"newSubscription": false,
"companyName": null
}'
Following doesn't do what I need:
Json.stringify()
jQuery doesn't have a method for JSON stringifying native objects. You will need json2.js which will provide the JSON.stringify() method to browsers that don't already support it.

Categories

Resources