Javascript accessing a nested object from ajax response - javascript

response._bodyText works, but I get undefined when I use response._bodyText.result

First you have to parse that because its in json format. Try
data = JSON.parse(response._bodyText)
data.result
For Reference you can study about JSON

you need to parse it
try
JSON.parse(response._bodyText).result

What you have inside response._bodyText is a stringified JSON.
To access the keys inside of it. you need to first parse it using JSON.parse
Example: JSON.parse('{ "hello":"world" }')
This will give you an object {hello: 'world'}
In your case you do JSON.parse upon response._bodyText, then you can access it just like a normal object.
JSON.parse(response._bodyText)

response._bodyText.result is undefined because _bodyText is a string.
You must first turn _bodyText into an object:
var body = JSON.parse(response._bodyText);
After that body.result should work.

Related

JavaScript object shows as a string instead of an item

So i am trying to display a data from an API using JavaScript but got an undefined instead when i console.log(data) what i am getting is like below. its an object but some how its encapsulate as a string? Any idea how to covert this into a actual object i am new with JavaScript api so i am a bit confused.
{"msg":"{\"part\":\"test\",\"station\":\"test2\"}"}
I already tried to de serialize the data using JSON.parse(data) but no luck.
What you have posted is actually an object with a property msg which is a strigified JSON. In order to get proper json from this try obj.msg = JSON.parse(obj.msg); Assuming obj is the response variable you can name it what you want.
See below snippet.
{"msg":"{\"part\":\"test\",\"station\":\"test2\"}"}
const obj = {"msg":"{\"part\":\"test\",\"station\":\"test2\"}"} ;
console.log('Before parsing:' + typeof obj.msg); // string
obj.msg = JSON.parse(obj.msg);
console.log('After Parsing:' + typeof obj.msg); // object
Hope this helps :)
JSON.parse transforms a string-like-object to the object. So, it expects the whole of the object as a string. Which is not happening in your case.
You have an object key msg and its value is a string-like-object. So You need to convert the msg value to the JSON.
a couple of ways to try -
let resp = JSON.parse(data.msg)
or
return JSON.parse(data.msg)

Accessing Elements of JS Object

I have created array in a object,
var obj_report_dailog = { array_report_dailog : [] }
Then push data to object,
obj_report_dialog.array_report_dialog.push({from: fromDate})
obj_report_dialog.array_report_dialog.push({to: toDate})
obj_report_dialog.array_report_dialog.push({fabrika: fabrika})
Then,
var json = JSON.stringify(obj_report_dialog);
How can I access to elements of that object?
console.log("işte bu: " + json);
output:
işte bu: {"array_report_dialog":[{"from":"2017-08-01"},{"to":"2017-09-21"},{"fabrika":["Balçova"]}]}
Two things:
You don't want to JSON.stringify unless you're sending the resulting string somewhere that will parse it. Remember, JSON is a textual notation for data exchange; JSON.stringify gives you a string to send to some receiver. When you have the JSON string, you don't access the properties of the objects in it.
If you're receiving that JSON string, you'd parse it via JSON.parse and then access the properties on the result.
Leaving aside the JSON thing, you probably don't want to add data the way you're adding it. You're adding three separate objects as three entries in the array, each with one property. You probably want to push one object with all three properties:
obj_report_dialog.array_report_dialog.push({
from: fromDate,
to: toDate,
fabrika: fabrika
});
Then you'd access them as obj_report_dialog.array_report_dialog[0].from, obj_report_dialog.array_report_dialog[0].to, and obj_report_dialog.array_report_dialog[0].fabrika. Or more likely, you'd have a loop like this:
obj_report_dialog.array_report_dialog.forEach(function(entry) {
// Use entry.from, entry.to, and entry.fabrika here
});
(See this answer for more options for looping through arrays.)
But, if you really want to push them as separate objects, you'd access them as obj_report_dialog.array_report_dialog[0].from, obj_report_dialog.array_report_dialog[1].to, and obj_report_dialog.array_report_dialog[2].fabrika (note the indexes going up).
If you stringify a json, it's gonna create a string representation of your object.
To access data in a string like that we usually use JSON.parse that create an json object from a string. Which is the obj_report_dailog you had at start.
You can make object from json by using JSON.parse()
JSON.parse(json).array_report_dialog

Access specific part of JSON JS

I am trying to access the t part of the "data": object below. I am doing this by doing console.log(message.data.f) however this returns undefined. I do not understand why I cannot access it in this way. See object below:
"data":"{\"e\":\"53845\",\"f\":\"SCORE\",\"pf\":[{\"p\":\"HOME\",\"v\":\"0\"},{\"p\":\"AWAY\",\"v\":\"0\"}],\"^t\":\"f\",\"i\":\"357575\",\"z\":1492771602631}",
Note I have marked the part of the object I wish to access with a ^
Your data property is a JSON string and probably all the object is a JSON string.
You need to parse the string as JSON
var obj = JSON.parse(myObj.data);
and then you can access:
console.log(obj.f);
If your first object, the one containing data, is not already a JSON too and its name is for example myFirstObject you need to do just this:
var jsonObj = JSON.parse(myFirstObject);
console.log(jsonObj.f);
Your message is nothing but string. Parse it first to a corresponding object to access its variables.
var parsed = JSON.parse(message);
console.log(message.data.t);

checking json value in javascript

var saurabhjson= JSON.stringify(data)
above returns this json
saurabhjson {"recordId":5555,"Key":"5656"}
if print the first array in console it get undefined value
console.log("saurabhjson[0].recordId",saurabhjson[0].recordId);
i want to do some check like this
if(saurabhjson[0].recordId == 5555) {
$('#div_ajaxResponse2').text("another success");
}
As the method suggests JSON.stringify(data). It converts a js object to a jsonstring now if you want a key out of this string it can't be done before parsing it to json.
So i don't get it why do you need to stringify it.
And another thing is you have a js object not an array of objects. so you need to use this on data itself:
console.log("data.recordId",data.recordId);
You are probably mixing a few things there.
When you do var saurabhjson= JSON.stringify(data), that saurabhjson variable is a string, not an object, so you can't access its elements like you are trying to do.
Try accessing data directly instead, without using JSON.stringify():
console.log("data.recordId",data.recordId);

Javascript JSON.parse or directly access

When we can read a property directly from string:
var data = {"id":1,"name":"abc","address":{"streetName":"cde","streetId":2}};
console.log(data.address.streetName); // cde
Why do people use JSON.parse:
var obj = JSON.parse(data);
console.log(obj.address.streetName); // cde
It is not a string, but Javascript object. String is given below
var data = '{"id":1,"name":"abc","address":{"streetName":"cde","streetId":2}}';
to make it object we use JSON.parse
var obj = JSON.parse(data);
console.log(obj.address.streetName); // cde
In your first example, data is an object, but in your second example, data is a JSON string.
That's a major difference. You could call eval(data) to parse a JSON string, but that's very unsafe.
JSON.parse() expects a string. More specifically, a string with a JSON-encoded piece of data.
If it's applied to an object then it's an error, the source of which is probably the common confusion that seems to exist between JavaScript objects and the JSON format.

Categories

Resources