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
Related
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.
I wish to store some data dynamically in an array, using Javascript. My goal is to save a configuration, that the user has specified, and later store it in my database.
I am trying to create a array like this:
var config = [];
config.push({id:100,name:'Yashwant',age:30});
config.push({id:200,name:'Mahesh',age:35});
However, when I print out the config array, like this:
alert(config);
it prints:
[object Object],[object Object]
How can I store and push values to my array, dynamically?
EDIT:: Seems like I am storing the values correctly. How can I access it?
Alert casts the config parameter to string. If you want to see the value for debugging purposes, it is better to use console.log(config).
Or you could use JSON.stringify(config) to convert it to JSON string.
To access the values, you can do this: console.log(config[0].age, config[1].age);
If you want to print values of any javascript object you can use JSON class to either stringify object data or parse stringified data (JSON) back to object.
alert(JSON.stringify(config));
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"]
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.
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