JSON object returns undefined value - javascript

I am receiving a JSON object from a http call and I am trying to extract values from it.
JSON object contains:
data:{"userid":"007", "role":"spy"}
I use the following code to assign role property to another variable followed by some console log checks:
currentUserRole = data.role;
console.log("type of data: "+typeof(data));
console.log("data: "+JSON.stringify(data));
console.log("user role: "+currentUserRole);
The logs produce:
type of data: object
data: [{"userid":"007", "role":"spy"}]
user role: undefined
Also I tried another method of assignment:
currentUserRole = data['role'];
But currentUserRole remains undefined. How can I set a property of a JSON object to a variable?

According to the second line of your log (the call to JSON.stringify()), your data is actually an array of objects:
[{"userid":"007", "role":"spy"}]
If it was an object as you are expecting, it would look like this:
{"userid":"007", "role":"spy"}
(the difference is subtle, but notice the missing square brackets)
Try this:
currentUserRole = data[0].role;
Obviously in production-ready code, you probably need to do some extra sanity checking to ensure that data is in fact an array containing at least one element.

It is a list. Try data[0].role

Related

How do I access object keys that show as undefined with direct reference to them but appear correctly when console logging?

I am doing an HTTPS request function and getting back an auth code I want to use.
I put the returned data from the request into a variable and when I console log the variable like so:
console.log(authResponse);
It produces:
{"auth_token":"gergerqv4rg","email":"newemail#email.com","first_name":"Guy","last_name":"Simpson"}
When I take that same variable and reference auth_token like so:
console.log(authResponse.auth_token);
Then it returns undefined. Going the same for email or the other keys produces the same result.
When I try something like:
Object.keys(authResponse)
It produces:
0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40, ... 154
Stopping at 154...
Trying to reference whatever that is produces random integers....
authResponse[0] = 123
authResponse[1] = 34
authResponse[2] = 97
authResponse[3] = 117
How do I reference my authResponse object's auth_token value?
console.log can make you think you've got an Object if the string is in the proper format. Be sure you are looking at an object, not a string.
When you determine the value is a String, parse the data into an object and you should be able to get the properties and values from it.
var authResponseObj = JSON.parse(authResponse);
console.log(authResponseObj.auth_token);

Javascript. Access variable values from javascript Object

I want to access a variable value of a Javascript object. The below image is a result of a console.log: console.log(variable).
I tried:
variable[0] -> returns undefined
Also tried converting using JSON.stringify -> shows '[]' on the console
Here's the screenshot of the value I want to get:
Assuming the array variable is the array of two objects, to get the string "tag1", you should try variable[0].name.

Name Indexes in Javascript - Array / Object?

I understand that when index names are used to push values in Javascript, they essentially work like objects. But what I don't understand is the following behaviour -
person = [];
person[0] = "Someone";
person["test"] = "SomeoneElse"
Inputting person on the console prints ["Someone"] and I could see no information about person.test.
person.test does print SomeoneElse. However, if I go console.log(person), I get ["Someone", test: "SomeoneElse"].
Curious to check if this makes sense, I tried to create a structure like this one -
var experiment = ["Someone1", test1: "SomeoneElse1"]
and what I get is
Uncaught SyntaxError: Unexpected token
What am I missing?
Thanks in advance!
Typing person on the console prints ["Someone"].
Array.prototype.toString formats this output, and it only considers the "array values" of itself without other properties.
However, if I go console.log(person), I get ["Someone", test: "SomeoneElse"].
console.log outputs other information about the object, including own properties.
Uncaught SyntaxError: Unexpected token
Because that is bogus syntax; the array literal syntax doesn't allow keys, because array values aren't supposed to have keys. Arrays are a numerically indexed list of values. Merely by the fact that under the hood those lists are implemented using objects (because everything in Javascript is an object of some kind or another) are you able to set "non numeric keys" on the array. That doesn't mean you're using the array correctly though.
Also see Are JavaScript Array elements nothing more than Array object properties?
This is because an array in JavaScript is also an object itself, and objects can have properties. So it is perfectly valid to have an array with elements, but also have properties set on the array object.
The second example doesn't work because the [...,...,...] syntax is specifically for instantiating an array and its elements.
typing person in console is like having an alert(person); or passing its value to a variable or element, so it is more like you want to get the first set of readable values. That is the reason why it is showing you the values inside, you can try adding person[1] = *something;*, then it will display someone, something
console.log(person) - it displays all the items inside an object. It is more like informing you of what is inside, like a text visualizer in your IDE
var experiment = ["Someone1", test1: "SomeoneElse1"] - it will absolutely throw an exception there is no such format like this on initializing values, at least it is expecting an array format like var experiment = ["Someone1", "SomeoneElse1"]

How do I attach JSON Stringify to a javascript variable

I have a variable :
var testData;
And I have a function that populates an array. Goes through an array and makes another array like so :
var person = {
"Name": obj.Name,
"Age": obj.Age,
}
partsObject.push(person);
I then want to make this array into JSON so I can use it with my D3 objects, so I do this :
testData = JSON.stringify(partsObject);
I can console log this variable, but when trying to go through it via D3's forEach method like so :
testData.forEach(function(d) // data is the JSON
{
I get the error Uncaught TypeError: testData.forEach is not a function
I don't understand how I can log the variable to the console yet it's as if I can't use it as JSON. Any ideas ?
As the name suggests stringify() converts a JavaScript object (the JSO in JSON) into a string of JSON. You can console.log() it because console.log expects to take a string, and anything that's not a string is converted to one to be displayed.
If you want to use it as an array again, you need to parse your string of JSON back to the JavaScript object: JSON.parse(testData).
You really dont need to stringify your Array to pass to d3. Do not to get confused with javascript objects, since forEach requires an array to loop through and you are passing a string to manipulate with forEach function
use:
partsObject.forEach(function(d)
{
...
JSON.stringify(partsObject); creates a string as"{'Name':'ABC','Age':23}"
Uncaught TypeError: testData.forEach is not a function caused because javascript was not able to find an Array
.stringify() turns a Javascript Object into a string. You would want to either run
partsObjects.forEach()
or alternativily you could turn the stringify'ed string back into an object with
(JSON.parse(testData)).forEach()
You are currently trying to loop through a String since you stringify your array.
Just do partsObject.forEach and don't stringify your Array.

JSON - There are no child objects

I am trying to retrieve some specific data, using jQuery to retrieve a JSON Feed.
This is what I am currently doing:
var url = 'https://api.wunderground.com/api/myapicode/conditions/forecast/q/Tokyo.json?callback=?';
$.getJSON(url, function(d){
var data = d['current_observation'];
console.dir(data['display_location']);
});
This successfully returns to the console:
city ==> "Tokyo"
country ==> "JP"
country_iso3166 ==> "JP"
elevation ==> "8.00000000"
full ==> "Tokyo, Japan"
latitude ==> "35.54999924"
etc...
However, let's say I want to get just the "full" name. If I try:
console.dir(data['display_location']['full']);
I end up getting the result: There are no child objects
Any ideas on what I am doing wrong here?
console.dir displays the properties (child objects) of the object you pass it.
It doesn't make sense to call it with a string.
You should call console.log instead.
You should be using console.log() to get a value instead of an object's properties.
console.dir will show object trees - the properties of the object you pass in. Yet, the property you log is just a string and has no child objects. Use console.log instead.
in order to use console.dir(arg) arg should be an object. You are accessing a full key of an object in console.dir(data['display_location']['full']); which is a plain string.
use console.log(data['display_location']['full']) instead

Categories