How to get key and value separately from json in node js - json

I have a json like this
{"Beauty_Personal_Care": {
"listingVersions": {
"v1": {
"get": "http://affiliate-feeds.snapdeal.com/feed/api/category/v1:586:680986904635?expiresAt=1455143400082&signature=gtvuofdhkeqxipadfzyf"
}
}
},
"Eyewear": {
"listingVersions": {
"v1": {
"get": "http://affiliate-feeds.snapdeal.com/feed/api/category/v1:473:630636448881?expiresAt=1455143400082&signature=gtvuofdhkeqxipadfzyf"
}
}
}
}
I want to get key value and objects of key value separately in node js backend.
Expected result:
name="Beauty_Personal_Care";
url="http://affiliate-feeds.snapdeal.com/feed/api/category/v1:586:680986904635?expiresAt=1455143400082&signature=gtvuofdhkeqxipadfzyf";

var json = {}; // your json
var result = [];
Object.keys(json).forEach(function (name) {
var data = {
name: name
};
data.url = json[name].listingVersions.v1.get;
result.push(data);
});
console.log(result);

Related

Add Property to Object in loop with Lodash in Express

I need to add a "id" property converted in kebab-case to an object parsed from a JSON file:
App.js
app.get('/factions', (req, res) => {
const rawData = fs.readFileSync(__dirname + '/views/data/factions.json');
var factions = JSON.parse(rawData);
for (var key in factions) {
factions.key["id"] = _.kebabCase(key);
}
console.log(factions);
res.render('pages/factions', {
factionList: factions
});
});
This way doesn't work, if I try factions["Faction One"]["id"] = _.kebabCase(key); I can see "id" : "faction-one" is added to Faction One. But if I use the key value doesn't.
JSON
{
"Faction One": {
"color": "blue"
},
"Faction Two": {
"color": "red"
}
}
Solved with
for (var key in factions) {
factions[key].id = _.kebabCase(key);
}

Extract parameters from nested Json

I have an json string, which looks like this:
{
\"request\": {
\"requestId\": \"dd92f43ec593d2d8db94193b7509f5cd\",
\"notificationType\": \"EntityAttribute\",
\"notificationSource\": \"ODS\"
},
\"entityattribute\": {
\"entityId\": \"123\",
\"attributeType\": \"DATE_OF_BIRTH\"
}
}
I want to deserialized entityattribute to an object:
public class EntityAttributeNotification {
private String attributeType;
private String entityId;
}
One way is to extract entityId and attributeType first using the json path(i.e entityattribute/entityId)and create an object EntityAttributeNotification.
I want to know if there is a way to directly deserialized entityattribute to EntityAttributeNotification.
I have also tried with JsonMixin annotation but this does not apply here.
Through the following method you can extract Parameters and Values of nested JSON .
const object1 ={
"request": {
"requestId": "dd92f43ec593d2d8db94193b7509f5cd",
"notificationType": "EntityAttribute",
"notificationSource": "ODS"
},
"entityattribute": {
"entityId": "123",
"attributeType": "DATE_OF_BIRTH"
}
};
var keys = [];
for (let [key, value] of Object.entries(object1)) {
if(typeof value == 'object'){
keys.push(key);
for (let [key1, value1] of Object.entries(value)) {
keys.push(key1);
}
}
else{
keys.push(key);
}
}
console.log(keys);

Mongo: Move json string to a part of the document

I have a mongo collection where documents have aprox the following structure:
item{
data{"emailBody":
"{\"uniqueKey\":\" this is a stringified json\"}"
}
}
What I want to do is to use 'uniqueKey' as an indexed field, to make an "inner join" equivalant with items in a different collection.
I was thinking about running a loop on all the documents -> parsing the json -> Saving them as new property called "parsedEmailBody".
Is there a better way to handle stringified json in mongo?
The only way is to loop through the collection, parse the field to JSON and update the document in the loop:
db.collection.find({ "item.data.emailBody": { "$type": 2 } })
.snapshot().forEach(function(doc){
parsedEmailBody = JSON.parse(doc.item.data.emailBody);
printjson(parsedEmailBody);
db.collection.updateOne(
{ "_id": doc._id },
{ "$set": { "item.data.parsedEmailBody": parsedEmailBody } }
);
});
For large collections, leverage the updates using the Bulk API:
var cursor = db.collection.find({ "item.data.emailBody": { "$type": 2 } }).snapshot(),
ops = [];
cursor.forEach(function(doc){
var parsedEmailBody = JSON.parse(doc.item.data.emailBody);
ops.push({
"updateOne": {
"filter": { "_id": doc._id },
"update": { "$set": { "item.data.parsedEmailBody": parsedEmailBody } }
}
});
if (ops.length === 500) {
db.collection.bulkWrite(ops);
ops = [];
}
});
if (ops.length > 0) { db.collection.bulkWrite(ops); }

Parsing JSON multi-level array

I want to search in json data with multiple levels of array. My search list return names of my objects but just from the first level. How could i do return all my object's names regardless their levels ?
In this example : OST, OST details, Apocalpse Now, Arizona Dream, Dexter
Data
<script type="application/json" id="dataMusic">
{
"name":"Music",
"level":"1",
"size":36184,
"children":[
{
"name":"OST",
"level":"2",
"size":1416,
"children":[
{
"name":"OST details",
"level":"3",
"size":1416,
"children":[
{
"name":"Apocalypse Now",
"size":15
},
{
"name":"Arizona Dream",
"size":19
},
{
"name":"Dexter",
"size":20
}
]
}
]
}
]
}
</script>
Function
var dataMusic = document.getElementById('dataMusic').innerHTML;
var dataTree = JSON.parse(dataMusic);
var optArray = [];
for (var i = 0; i < dataTree.children.length - 1; i++) {
optArray.push(dataTree.children[i].name);
}
optArray = optArray.sort();
I try this method Parsing Nested Objects in a Json using JS without success
Function
var optArray = [], Music, OST, OST details;
for (Music in dataTree) {
for (OST in dataTree[Music]) {
for (OST details in dataTree[Music][OST]) {
if (OST details in optArray) {
optArray[OST details].push(dataTree[Music][OST][OST details].name)
} else {
optArray[OST details] = [dataTree[Music][OST][OST details].name]
}
}
}
}
You must use nested loops
for Music.children.length
for OST.children.length
for OST details.children.length
Edit : Function
var optArray = [], Music, OST, OST_details;
for (Music in dataTree) {
for (OST in dataTree[Music]) {
for (OST_details in dataTree[Music][OST]) {
if (OST_details in optArray) {
optArray[OST_details].push(dataTree[Music][OST][OST_details].name)
} else {
optArray[OST_details] = [dataTree[Music][OST][OST_details].name]
}
}
}
}
I got it
var dataMusic = document.getElementById('dataMusic').innerHTML;
var dataTree = JSON.parse(dataMusic);
var result = [];
function getAll( input, target ) {
function parseData( input, target ) {
$.each( input, function ( index, obj ) {
if ( index == target ) {
result.push( obj );
}
else {
switch ( $.type( obj ).toLowerCase() ) {
case "object":
case "array":
parseData( obj, target );
break;
}
}
});
}
parseData( dataTree, "name" );
result = result.sort();
return result;
}
alert(JSON.stringify( getAll( dataTree, "name" )));
Thanks to this post :
Parsing multi-level json ; Demo

Loop to add data to complex JSON object

I have a complex JSON Object like this:
var requestData = { __batchRequests: [ { __changeRequests: [
{ requestUri: "Customers", method: "POST", headers: { "Content-ID": "1" }, data: {
CustomerID: 400, CustomerName: "John"
} }
] } ] };
I am trying to do two things:
Declare this object but with the variable data empty
With a loop, add items dynamically to the data object,
How can I do it?
This isn't too complex an object. And it isn't JSON until it's converted into a string.
Right now, it's just plain-ol' JS objects and arrays.
Breaking that down into its elements might look like this:
var requestData = {};
requestData.__batchRequests = [];
requestData.__batchRequests[0] = {};
requestData.__batchRequests[0].__changeRequests = [];
requestData.__batchRequests[0].__changeRequests[0] = {};
requestData.__batchRequests[0].__changeRequests[0].requestUri = "Customers";
requestData.__batchRequests[0].__changeRequests[0].method = "POST";
requestData.__batchRequests[0].__changeRequests[0].headers = { "Content-ID" : "1" };
requestData.__batchRequests[0].__changeRequests[0].data = {};
Aside from the repeats, what do you see?
Personally, I see that __changeRequests[0] is an object as simple as:
var changeRequest = {
requestUri : "Customers",
method : "POST",
headers : { "Content-ID" : "1" },
data : {}
};
I also see that I can just push that onto my array of change requests:
requestData.__batchRequests[0].__changeRequests.push(changeRequest);
Right?
I also know that my changeRequest variable still points to the one that I just added to the array, and whatever I change on the object will show up as changed in the array's reference to the object, too:
changeRequest.data.CustomerName = "Bob";
changeRequest.data.CustomerID = "204";
requestData.__/*...*/changeRequests[0].data.CustomerName; // Bob
So how about writing yourself some helper-functions?
function extend (obj, additions) {
var key;
for (key in obj) { if (additions.hasOwnProperty(key)) {
obj[key] = additions[key];
}
}
function makeChangeRequest (url, method, headers, data) {
var request = {
requestUri : url,
method : method,
headers : {},
data : {}
};
extend(request.headers, headers);
extend(request.data, data);
return request;
}
function getBatch (num) { return requestData.__batchRequests[num]; }
var changeReq = makeChangeRequest("Customers",
"POST",
{ "Content-ID" : "1" },
{ CustomerName : "Bob", CustomerID : "2012" });
var batch = getBatch(0);
batch.__changeRequests.push(changeReq);
If you want to add more data to changeReq.data later:
extend(changeReq.data, { Address : "33 Nowhere Rd.", City : "Splitsville" });
For the first part of your question, you can initialize data with an empty associative array:
var requestData = { __batchRequests: [ { __changeRequests: [
{ requestUri: "Customers", method: "POST", headers: { "Content-ID": "1" }, data: {} }
] } ] };
This next part assumes, perhaps incorrectly, that you can use jQuery. It also assumes that you have an array containing all of the relevant key value pairs.
var customerDeetsArray =[{CustomerID: 400}, {CustomerName: "John"}];
for (var i in customerDeetsArray) {
requestData.data = $.extend(requestData.data, customerDeetsArray[i]);
}
See working example which makes use of console.debug:
http://jsfiddle.net/4Rh72/6/