JSON stringify skip nested object which has more than 3 levels - javascript

I wanted to store the object in local storage and I serialized the object using JSON.stringify. Then some of the inner attributes are missing after parse using JSON.parse.
I attached 2 images below to see the changes and appreciate it if anyone can answer a better solution for this. Thanks.
This object is just before stringified using JSON.
This object is stringified and parse using JSON
This is how i store and retreive data

Json.Stringify does not pass functions into the stringified JSON, i.e. functions will not be copied into the string as functions are not valid JSON objects. In your case, the difficulty is a function and as such won't be copied.
You can include the function by using a replacer:
JSON.stringify({
/* your object here */
}, function(key, val) {
return (typeof val === 'function') ? '' + val : val;
});

Related

CognitiveServices POST response: data.hasOwnProperty failing for all but root of nested JSON object using raw JS

I am posting a request to Azure Cognitive Services (sentiment API) which returns a nested JSON object as follows (this is a JSON.stringify object output):
{ "error": "{\"documents\":[{\"id\":\"1\",\"sentiment\":\"neutral\",\"documentScores\":{\"positive\":0.15,\"neutral\":0.8,\"negative\":0.05},\"sentences\":[{\"sentiment\":\"neutral\",\"sentenceScores\":{\"positive\":0.15,\"neutral\":0.8,\"negative\":0.05},\"offset\":0,\"length\":4}]}],\"errors\":[],\"modelVersion\":\"2019-10-01\"}" }
I have spent 3 days trying and failing to access the nested key:values using javascript, so I can write individual keys/values to HTML elements using raw JS.
I've validated the JSON is correct using jsonlint.com
I've tried removing '/' characters by both re-parsing, and .replace, but the "cleaned" JSON still does not provide access to documents[]
I've used the following function, found on SO, to validate the stringify string against the object:
//Get nested object structure with key names
function traverse_it(data){
for(var prop in data){
if(typeof data[prop]=='object'){
// object
traverse_it(data[prop[i]]);
}else{
// something else
alert('The value of '+prop+' is '+data[prop]+'.');
}
}
}
traverse_it(data);
I've used data.hasOwnProperty to test for property existence - the only property that returns TRUE is "error":
//Check for individual properties
if(data.hasOwnProperty("error")){
console.log(data.error);
alert('yippidydippity')
}else{
alert('nope')
}
Attempts to access error.documents, error.documents[0].id, or locate the documents array all fail. I've searched through similar problems on SO but have not found anything that works.
How can I access the individual keys and values of this object using JS? Many thanks in advance!!!
try this
let obj = { "error": "{\"documents\":[{\"id\":\"1\",\"sentiment\":\"neutral\",\"documentScores\":{\"positive\":0.15,\"neutral\":0.8,\"negative\":0.05},\"sentences\":[{\"sentiment\":\"neutral\",\"sentenceScores\":{\"positive\":0.15,\"neutral\":0.8,\"negative\":0.05},\"offset\":0,\"length\":4}]}],\"errors\":[],\"modelVersion\":\"2019-10-01\"}" }
let obj2 = JSON.parse(obj.error)
//now you can access id from object
console.log(obj2.documents[0].id)

JSON / JavaScript get object keys

I'm extracting data from as follows -
The above function returns data in the below format -
[Object { date=Date, value=112, volume=1469}, Object { date=Date, value=124, volume=539}, Object { date=Date, value=114, volume=859}, Object { date=Date, value=123, volume=1284}, Object { date=Date, value=113, volume=1382}, Object { date=Date, value=129, volume=1353}]
I would like to obtain the list of keys only as a simple array.(Parsing the first object in the array is enough to get this as all other objects have the same keys) In case of the above output, I would like the simple array to look as ["date","value","volume"]
I tried JSON.stringify & then parse but it still doesn't work.
Also, how could I convert the whole array obtained from the chart into a simple array please?
I'm visualizing an output of the below type -
[{'date':'whatever', 'value':126, 'volume':911},
{'date':'whatever', 'value':136, 'volume':1005},
{'date':'whatever', 'value':125, 'volume':720}]
If the question doesn't make sense, please let me know. I'll see how best I could re-word.
Use Object.keys() function. Here in the response from function you get an array. Use that to get the list of keys.
var data = getChartData('param')
Object.keys(data[0]);

JSON Object not fully converts to String?

I am facing an issue that JSON.stringify not stringifies all the keys in a JSON Object.
ie. window.performance.getEntries()[0] contains around 17 keys. But on converting to a string, the result contains only 4 keys.
How can I convert all the keys in window.performance.getEntries()[0]?
I want the complete string output of window.performance.getEntries() which is an array and I used JSON.stringify(window.performance.getEntries()).
Thanks in advance..
window.performance seems to have is own toJSON-function and so can determine what will be stringified. Here is a answer and a work around to your question from a similiar question: https://stackoverflow.com/a/20511811/3400898
"If the stringify method sees an object that contains a toJSON method, it calls that method, and stringifies the value returned. This allows an object to determine its own JSON representation."
As other stated it is because there is a toJSON method defined. Basically you need to loop over every index of the array and than every property in the object.
var adjusted = window.performance.getEntries().map( function (result) {
var temp = {}, key;
for (key in result) if (key!=="toJSON") temp[key]=result[key];
return temp;
});
console.log(JSON.stringify(adjusted[0]));
The simplified solution for this problem which I found is
var jsonArray = $.map(performance.getEntries(),function(jsonObj){
var obj = $.extend({},jsonObj);
delete obj.toJSON;
return obj;
});
JSON.stringify(jsonArray);

Access JSON object to get Resource Bundle key/value pair

I know how to access key value pair from JSON object but in my case, the resource bundle keys are mapped to values.
e.g.
var json = {"label.name.first":"foo","label.name.second":"bar"};
Here json.label.name.first doesn't give me "foo".
Can someone help me with this?
Due to using the period character (.) in the key name, you need to use the [] notation to access its value.
console.log( json['label.name.first'] );
Additionally, you have a JavaScript object, not JSON.
The difference between a JavaScript object or JSON is that JSON is always a string. Secondly, JavaScript objects don't require the same quote standards on the key names.
If you just consider the string below, then yes it can be considred JSON (this is why if you paste it into a JSON parser, it tells you it's valid JSON):
{"label.name.first":"foo","label.name.second":"bar"}
However, if you assign that directly to a JavaScript variable then you have a JavaScript object literal, not JSON. This is because JSON is also a valid JavaScript object/array literal when it is not contained in a string:
var obj = {"label.name.first":"foo","label.name.second":"bar"};
If you were to use it as a string, then it is JSON:
var json = '{"label.name.first":"foo","label.name.second":"bar"}';
// json is a string, so it's JSON
var obj = JSON.parse(json); // parse the JSON into an object
The confusion is quote common because the JSON format is very similar to the format of JavaScript object and array literals.
Do this:
json["label.name.first"]
However, I think you are misunderstanding the . notation.
And BTW your json isn't a JSON, it is a javascript object and not its notation.
It's json["label.name.first"] that would get you "foo". Since your property's name contains characters that cannot be used in variable names.
If you're expecting to access these properties using the syntax json.label.name.first then your JSON needs to be:
var json = {
"label":{
"name":{
"first":"foo",
"second":"bar"
}
}
}
This is not right way to create object, you should create one like this.
var json={"label":{"name":{"first":"foo","second":"bar"}}};
it will also work as json string

JavaScript - Converting JSON object to String

I have a JSON object in following format which I need to convert to pure String...as 0000-0000-0000-0000-000 so I was wondering how I can do this in Javascript?
{ KEY: "0000-0000-0000-0000-000" }
try this (where data is the data returned from the API call)
var tokenString = data.KEY;
alert(tokenString);
try
console.log(obj)
to view it in the browser debugger console
or
JSON.stringify(obj);
I would recommend using
JSON.stringify()
Extra info on this method can be found here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify
Your object is not JSON when it's in JavaScript, it's JavaScript code. The string version you're asking for is JSON (JavaScript Object Notation). This is why you can do things in JavaScript that you cannot do in JSON, like representing functions and binary data.
The function you're looking for to turn your JavaScript object into JSON is JSON.stringify() which you would use like this:
var obj = { }; //put your object here
console.log(JSON.stringify(obj)); //output the JSON version of your object
Also, the object in your question is not valid JSON or JS. In either scenario you'd need to put quotes around the 0000-0000-0000-0000-0000 and give it a value. The following is valid JSON:
{ "0000-0000-0000-0000-0000": null }
Store your response in one variable and then do
response.KEY

Categories