How to access JS Object value in nestted object? - javascript

I am having trouble accessing the data in this JS Object. I can get this data by accessing data.queryParams. But if I try to drill lower, I get undefined. Below is what shows up if I do a JSON.stringify(data.queryParams). I've tried data.queryParams.attributes, data.queryParams[0], data.queryParams.handle, etc. And I get undefined for all of them.
console.log(data)
Object {
"hostname": "127.0.0.1",
"path": null,
"queryParams": Object {
"{\"attributes\":[{\"handle\":\"email\",\"name\":\"Email\",\"value\":\"test#test.com\"},{\"handle\":\"fname\",\"name\":\"First Name\",\"value\":\"Luke\"},{\"handle\":\"lname\",\"name\":\"Last Name\",\"value\":\"Skywalker\"},{\"handle\":\"zip\",\"name\":\"Postal Code\",\"value\":\"73067-9895\"},{\"handle\":\"uuid\",\"name\":\"Unique Identifier\",\"value\":\"XXXXXXXXXXXX\"}],\"status\":[{\"group\":\"penguins\",\"subgroups\":[\"King penguins\"],\"verified\":true}]}": "",
},
"scheme": "exp",
}
console.log(data.queryParams)
Object {
"{\"attributes\":[{\"handle\":\"email\",\"name\":\"Email\",\"value\":\"test#test.com\"},{\"handle\":\"fname\",\"name\":\"First Name\",\"value\":\"Luke\"},{\"handle\":\"lname\",\"name\":\"Last Name\",\"value\":\"Skywalker\"},{\"handle\":\"zip\",\"name\":\"Postal Code\",\"value\":\"73067-9895\"},{\"handle\":\"uuid\",\"name\":\"Unique Identifier\",\"value\":\"42e97018b6604fe491b82b629ad65c23\"}],\"status\":[{\"group\":\"penguins\",\"subgroups\":[\"King penguins\"],\"verified\":true}]}": "",
}

i think something wrong with your response, your data is set as key of the Object.
const obj = {
"hostname": "127.0.0.1",
"path": null,
"queryParams": {
// below is your data as key
"{\"attributes\":[{\"handle\":\"email\",\"name\":\"Email\",\"value\":\"test#test.com\"},{\"handle\":\"fname\",\"name\":\"First Name\",\"value\":\"Luke\"},{\"handle\":\"lname\",\"name\":\"Last Name\",\"value\":\"Skywalker\"},{\"handle\":\"zip\",\"name\":\"Postal Code\",\"value\":\"73067-9895\"},{\"handle\":\"uuid\",\"name\":\"Unique Identifier\",\"value\":\"XXXXXXXXXXXX\"}],\"status\":[{\"group\":\"penguins\",\"subgroups\":[\"King penguins\"],\"verified\":true}]}": "",
},
"scheme": "exp",
};
let value = Object.keys(obj.queryParams)[0]; // <-- get your data
value = JSON.parse(value); // <-- set to JSON
console.log(value.attributes) // <-- test log attributes
but better if you can fix the response

Try with JSON.parse to convert your JSON string to an object, then you can access your data
let attributes = JSON.parse(data.queryParams).attributes;
console.log(attributes)

Related

Embedded Objects to Arrays

I was given an existing project where the data structure is below:
[
{
"key": "username",
"value": ""
},
{
"key": "password",
"value": ""
},
{
"key": "cars",
"value": [
{"ABC-1234-1234": "s4LmoNzee9Xr6f7uu/"},
{"ABC-5678-5678": "s5LmoNzee9Xr5f9uu/"}
]
}
]
Cars' value is an array of objects.
To create the initial object in the cars' array, I do the following:
var encryptedStuff = json.data;
var carkey = carid;
var entry = {};
entry[carkey] = encryptedStuff;
var carArray = [];
key="cars";
carArray.push(entry);
I need to push the array into another function that turns it into a string in a stored variable.
My problem...and I'm really rusty on embedded objects...is to do the following:
1.) Get the string
2.) JSON.parse back into an object (I got this far as I'm using a jQuery grep but I'd prefer to use JavaScript).
Here's my problem...
3.) locate the cars key in the object and get its value.
4.) Turn the value into an array to either delete an item or to add one (as per the code above where I'm writing the object into the array.
In the case of adding, I would have to copy the cars' value into the carArray[] and then push the new item into it.
In the case of deleting, I would have to remove the item and push back everything back into the carArray[].
I would do things differently but I can't change the structure of the data as this is approved company-wide.
Any help would be appreciated.
Thanks
You don't need to make a copy of the car's value array to add new entries nor make a copy then "push back" to remove an entry - you can reference it directly in the parsed object.
You can use
JSON.parse
array.find
array.push
array.splice
JSON.stringify
Giving:
var source = `[
{
"key": "username",
"value": ""
},
{
"key": "password",
"value": ""
},
{
"key": "cars",
"value": [
{"ABC-1234-1234": "s4LmoNzee9Xr6f7uu/"},
{"ABC-5678-5678": "s5LmoNzee9Xr5f9uu/"}
]
}
]`
// convert json to an object
var data = JSON.parse(source);
console.log(data, data.find(e=>e.key=="cars").value)
// add an item to the cars.value
data.find(e=>e.key=="cars").value.push({"ABC-": "s6..." });
// remove an item from the cars.value
data.find(e=>e.key=="cars").value.splice(1,1);
// confirm items added/removed
console.log(data, data.find(e=>e.key=="cars").value)
// convert back to a strng to send back to the service
var result = JSON.stringify(data);
console.log(result);

Adding a new object into a nested array

I want to add a new object for each nested array. I'm calling this function any time I add a product to my orderintake:
add2order(productID, productName, productRatePlans) {
this.orderIntake.push({ productID, productName, productRatePlans });
let i = 0;
this.orderIntake[0].productRatePlans[0].productRatePlanCharges.forEach(element => {
i++;
this.orderIntake[0].productRatePlans[0].productRatePlanCharges[
i
].quantity = this.orderIntake[0].productRatePlans[0].productRatePlanCharges[
i
].defaultQuantity;
});
}
this is an example response from the server:
{
"id": "8adc8f996928b9a4016929c59b943a8f",
"sku": "SKU-00006778",
"Partner_Account_ID__c": null,
"productRatePlans": [
{
"id": "8adce4216928c28d016929c59bff3372",
"status": "Active",
"name": "Enterprise",
"description": null,
"effectiveStartDate": "2016-02-26",
"effectiveEndDate": "2029-02-26",
"productRatePlanCharges": [
{
"id": "8adc8f996928b9a4016929c59d183a92",
"name": "USAGE_COUNTER_2",
"type": "Usage",
"model": "Volume",
"uom": "Each",
"pricingSummary": [
"Up to 5000 Each: USD0 flat fee"
],
"pricing": [
{
...
}
],
"defaultQuantity": null,
"applyDiscountTo": null,
"discountLevel": null,
"discountClass": null,
...
"financeInformation": {
..,
}
}
]
}
],
"productFeatures": [
{
...
}
]
}
The data is being retrived this way from an external REST backend so unfortunately I can't initialize the data including the new property...
so in every productRatePlanCharges there should be 1 new object 'quantity'.
How can I add this field to every productRatePlanCharges?
Right now I'm getting: ERROR
TypeError: Cannot read property 'productRatePlanCharges' of undefined
And how can I make sure I'm always adding this to the last orderIntake element? Don't mind productRatePlans there is only 1 in each orderintake...
thanks for your support!
Here you have to create productDetails object with inititalised array like below so that you won't get the error.
add2order(productID, productName, productRatePlans) {
// Create object like below
let productDetails = { productID : productID, productName : productName, productRatePlans : productRatePlans
}
this.orderIntake.push(productDetails);
let i = 0;
this.orderIntake[0].productRatePlans[0].productRatePlanCharges.forEach(element => {
i++;
this.orderIntake[0].productRatePlans[0].productRatePlanCharges[
i
].quantity = this.orderIntake[0].productRatePlans[0].productRatePlanCharges[
i
].defaultQuantity;
});
}
Hope this will help!
as you used Angular you probably use Typescript too. I recommend that you create a model like your incoming model and there define your quantity: number inside productRatePlanCharges object. then map the incoming data to your own model. therefore you will have a quantity=0 in your model that you can change it later in a loop.
If you want to continue with your own way take a look at this:
Add new attribute (element) to JSON object using JavaScript
there is no problem to add an element to current model almost like you did, and the problem might be somewhere else as your error refers to existence of productRatePlanCharges!
as you used forEach I prefer to use that 'element' and double iterating with i++; is not a good idea to me.
this might be better:
element.quantity = element.defaultQuantity;

Can't access JSON Object no matter what i'm trying

So i have this JSON Structure, which i want to access:
data { payload: "{"state":{"reported":{"measuredata":{…
JSON.parse doesnt work, neither does JSON.stringify.
i only can access payload, if i go any further, i receive error or undefined:
data.payload // works
data.payload["state"] //undefined
data.payload.state // undefined
data.payload[0].state // undefined
data.payload[0]["state"] // undefined
what am i doing wrong?
the thing that i can see is that you have a bad format on your json data { payload: "{"state":{"reported":{"measuredata":{…
it hspuld be witouth the double quote that be after the word payload payload: "{"state"
you have to have something like this
payload: {"state"
You just need to use JSON.parse for payload json string value.
JSON.parse(data.payload).state;
Sample code for parsing.
var data = {
"logged_in":true,
"town":"Dublin",
"state":"Ohio",
"country":"USA",
"products":
{
"pic_id":"1500",
"description":"Picture of a computer",
"localion":"img.cloudimages.us/2012/06/02/computer.jpg",
"type":"jpg",
"childrenimages":
{
"pic_id":"15011",
"description":"Picture of a cpu",
"localion":"img.cloudimages.us/2012/06/02/mycpu.png",
"type":"png"
}
}
};
var data1 = JSON.stringify(data);
var data_final = JSON.parse(data1);
console.log(data_final.products.pic_id);

Check if JSON object exist (Postman)

I am trying to write a test in Postman to check if JSON keys are present in the response I received from the server.
The response:
{
"Result": 0,
"ResponseStatus": {
"ErrorCode": null,
"Message": null,
"StackTrace": null,
"Errors": null
},
"ResponseHeader": {
"Succeeded": true,
"Errors": null
},
"SessionId": "XXX-XXX-XXX"
}
I want to check "Results, Errorcode, Message,Succeeded" etc..
Thanks!
You could check the response scheme using:
var jsonData = JSON.parse(responseBody);
tests['response json contain Results'] = _.has(jsonData, 'Results');
According to your response body that you get, You can write simple test script for request under test section.
You need to parse your json response first. The script will look like:
var jsonData = JSON.parse(responseBody);
tests["Succeeded with value true"] = jsonData.ResponseHeader.Succeeded === true;
similarly you can write tests for other checks.For sessionId I would suggest you to check it with sessionId where it gets generated(store it in environment and check with it in this request)

How to interpret JSON field with '-' in node.js

I am using the node.js to interpret a JSON data, the data format is like this below
{
"href": "https://localhost/light/0000293D",
"i-object-metadata": [
{
"rel": "temperature",
"val": "244"
}
]
}
I can print the raw data using print (body)
to interpret data all works except printing the field i-object-metadata
var obj = JSON.parse(body);
console.log(obj.items); // works well
console.log(obj.i-object-metadata); // error
How could I interpret the JSON object like this i-object-metadata
Can't use the object shorthand in this case, you'll have to use the array notation:
console.log(obj['i-object-metadata'].val); // 244

Categories