Well, this should be so simple. If you keep JSON data in a Javascript variable, then the way you tried should work. See my version of it.
var jsonData = {
"page" : 1,
"results" : [{
"adult" : false,
"backdrop_path" : "/fLL6WfUXvdQee1fD4xuzNnWfVBk.jpg",
"genre_ids" : [27, 9648, 80],
"id" : 176,
"original_language" : "en",
"original_title" : "Saw",
"overview" : "Obsessed with teaching his victims the value of life, a deranged, sadistic serial killer abducts the morally wayward. Once captured, they must face impossible choices in a horrific game of survival. The victims must fight to win their lives back, or die trying...",
"release_date" : "2004-01-19",
"poster_path" : "/dHYvIgsax8ZFgkz1OslE4V6Pnf5.jpg",
"popularity" : 2.897462,
"title" : "Saw",
"video" : false,
"vote_average" : 7.1,
"vote_count" : 657
}, {
"adult" : false,
"backdrop_path" : "/yKATxJtGY67cXdOmlbWwW6EgPqn.jpg",
"genre_ids" : [27, 53, 80],
"id" : 663,
"original_language" : "en",
"original_title" : "Saw IV",
"overview" : "Jigsaw and his apprentice Amanda are dead. Now, upon the news of Detective Kerry's murder, two seasoned FBI profilers, Agent Strahm and Agent Perez, arrive in the terrified community to assist the veteran Detective Hoffman in sifting through Jigsaw's latest grisly remains and piecing together the puzzle. However, when SWAT Commander Rigg is abducted and thrust into a game, the last officer untouched by Jigsaw has but ninety minutes to overcome a series of demented traps and save an old friend...or face the deadly consequences.",
"release_date" : "2007-10-25",
"poster_path" : "/veApHw5ARGHWf3ptKf30rOGFY9n.jpg",
"popularity" : 2.449196,
"title" : "Saw IV",
"video" : false,
"vote_average" : 5.8,
"vote_count" : 257
}
]
};
console.log(jsonData.results[0].id);
console.log(jsonData.results[1].id);
Answer from Beroza Paul on Stack OverflowWell, this should be so simple. If you keep JSON data in a Javascript variable, then the way you tried should work. See my version of it.
var jsonData = {
"page" : 1,
"results" : [{
"adult" : false,
"backdrop_path" : "/fLL6WfUXvdQee1fD4xuzNnWfVBk.jpg",
"genre_ids" : [27, 9648, 80],
"id" : 176,
"original_language" : "en",
"original_title" : "Saw",
"overview" : "Obsessed with teaching his victims the value of life, a deranged, sadistic serial killer abducts the morally wayward. Once captured, they must face impossible choices in a horrific game of survival. The victims must fight to win their lives back, or die trying...",
"release_date" : "2004-01-19",
"poster_path" : "/dHYvIgsax8ZFgkz1OslE4V6Pnf5.jpg",
"popularity" : 2.897462,
"title" : "Saw",
"video" : false,
"vote_average" : 7.1,
"vote_count" : 657
}, {
"adult" : false,
"backdrop_path" : "/yKATxJtGY67cXdOmlbWwW6EgPqn.jpg",
"genre_ids" : [27, 53, 80],
"id" : 663,
"original_language" : "en",
"original_title" : "Saw IV",
"overview" : "Jigsaw and his apprentice Amanda are dead. Now, upon the news of Detective Kerry's murder, two seasoned FBI profilers, Agent Strahm and Agent Perez, arrive in the terrified community to assist the veteran Detective Hoffman in sifting through Jigsaw's latest grisly remains and piecing together the puzzle. However, when SWAT Commander Rigg is abducted and thrust into a game, the last officer untouched by Jigsaw has but ninety minutes to overcome a series of demented traps and save an old friend...or face the deadly consequences.",
"release_date" : "2007-10-25",
"poster_path" : "/veApHw5ARGHWf3ptKf30rOGFY9n.jpg",
"popularity" : 2.449196,
"title" : "Saw IV",
"video" : false,
"vote_average" : 5.8,
"vote_count" : 257
}
]
};
console.log(jsonData.results[0].id);
console.log(jsonData.results[1].id);
It is a better practice to check the datatype of the variable one is about to parse using typeOf json==='object', if it is a valid object then you can do further manipulations or else parse it using json=JSON.parse(json);
Well, you either have a JSON string or a Javascript object. There is no such thing as a "JSON object" - JSON is a string notation for encoding a Javascript Object.
If you have a JSON string, you need to turn it into a Javascript Object - search SO for numerous examples.
If you have a Javascript object, you can access attributes via the dot notation, or array notation. E.g.
var obj = { 'foo' : 'bar', 'foo2' : { 'foo3' : 'bar2' }};
obj.foo; // 'bar';
obj['foo']; // 'bar';
obj.foo2['foo3']; // 'bar2';
Parse the JSON string first:
var msgs = JSON.parse(json);
Since JSON strings are simply dictionaries/associative arrays, you can just get the values in javascript by doing something like:
var value = msgs["key"];
In your case, it seems like the value is nested inside multiple dictionaries, so perhaps something like:
var customerName = msgs["SOAP-ENV:Body"]["@attributes"]["bill"]["customerDetil"]["customerFirstName"];
You have it the wrong way round - JSON.stringify turns a javascript object to a string. And JSON.parse parses a JSON String to a javascript object.
Also, having done that, if you want to read a property using a string use square bracket notation:
var jsonData = JSON.parse(data);
var jsonVar = "jVar";
for (var l = 0; l < jsonData[jsonVar].length; l++) {
var arrayItem = jsonData[jsonVar][l];
...
}
(As an aside l is a bad choice for a loop control variable - looks too much like a 1)
Make sure you have a valid JSON object first. I don't think what you have is valid to start with.
JSON.parse(yourValidJsonObject);
The above should give you a plain Javascript object you can work with.
Whereas, JSON.stringify(yourPlainJavascriptObject) will turn the plain js object to a JSON object.
var json=[{"id":0,"date":"05-11-2018","total":0},{"id":1,"date":"06-11-2018","total":0},{"id":2,"date":"07-11-2018","total":0},{"id":3,"date":"08-11-2018","total":0},{"id":4,"date":"09-11-2018","total":0},{"id":5,"date":"10-11-2018","total":0},{"id":6,"date":"11-11-2018","total":0}];
for(var i = 0; i < json.length; i++) {
var obj = json[i];
console.log(obj.date);
}
You can parse json object by using their key value. to get value from this object
for(var i in response ) {
// to print only date from every object
console.log(response[i].date)
}
and also your response is an json array so get second object by
response[1].date
JSON content is basically represented as an associative array in JavaScript. You just need to loop over them to either read the key or the value:
var JSON_Obj = { "one":1, "two":2, "three":3, "four":4, "five":5 };
// Read key
for (var key in JSON_Obj) {
console.log(key);
console.log(JSON_Obj[key]);
}
First off, you're not dealing with a "JSON object." You're dealing with a JavaScript object. JSON is a textual notation, but if your example code works ([0].amount), you've already deserialized that notation into a JavaScript object graph. (What you've quoted isn't valid JSON at all; in JSON, the keys must be in double quotes. What you've quoted is a JavaScript object literal, which is a superset of JSON.)
Here, length of this array is 2.
No, it's 3.
So, i need to get the name (like amount or job... totally four name) and also to count how many names are there?
If you're using an environment that has full ECMAScript5 support, you can use Object.keys (spec | MDN) to get the enumerable keys for one of the objects as an array. If not (or if you just want to loop through them rather than getting an array of them), you can use for..in:
var entry;
var name;
entry = array[0];
for (name in entry) {
// here, `name` will be "amount", "job", "month", then "year" (in no defined order)
}
Full working example:
(function() {
var array = [
{
amount: 12185,
job: "GAPA",
month: "JANUARY",
year: "2010"
},
{
amount: 147421,
job: "GAPA",
month: "MAY",
year: "2010"
},
{
amount: 2347,
job: "GAPA",
month: "AUGUST",
year: "2010"
}
];
var entry;
var name;
var count;
entry = array[0];
display("Keys for entry 0:");
count = 0;
for (name in entry) {
display(name);
++count;
}
display("Total enumerable keys: " + count);
// === Basic utility functions
function display(msg) {
var p = document.createElement('p');
p.innerHTML = msg;
document.body.appendChild(p);
}
})();
Run code snippetEdit code snippet Hide Results Copy to answer Expand
Since you're dealing with raw objects, the above for..in loop is fine (unless someone has committed the sin of mucking about with Object.prototype, but let's assume not). But if the object you want the keys from may also inherit enumerable properties from its prototype, you can restrict the loop to only the object's own keys (and not the keys of its prototype) by adding a hasOwnProperty call in there:
for (name in entry) {
if (entry.hasOwnProperty(name)) {
display(name);
++count;
}
}
customers is an array, to access array elements you need to write the index into square brackets behind it. In this case, if you want to access the first element (index 0) of the array, you can do that like so:
$http.get('url').
then(function successCallback(response){
var costumers = response;
console.log(costumers['data']['costumers'][0]['name']);
}, function errorCallback(response){
});
Or log all customers by using a for loop:
$http.get('url').
then(function successCallback(response){
var costumers = response;
for(let customer of costumers['data']['costumers']) {
console.log(customer['name']);
}
}, function errorCallback(response){
});
All of this only works if the object is syntactically correct, it should look like this:
{data: {costumers:[{id:"1",name:"John"},{id:"2",name:"Mary"}]}}
Instead of the object you posted.
The costumers in your case is an array of objects, so you have to specify the index of the object you want to target to get the values from, example :
costumers['data']['costumers'][0]['name']
______________________________^^^
The 0 index will return the first object :
{"id":"1","name":"John"}
You could always loop through all the objects of costumers, and you can check if the returned object has the 'attribute' you want like :
if( costumers['data']['costumers'][0].hasOwnProperty('name') ){
console.log( costumers['data']['costumers'][0]['name'] );
}
var obj = [
{
"disclaimer": "This data is collected from various providers and provided free of charge for informational purposes only, with no guarantee whatsoever of accuracy, validity, availability, or fitness for any purpose; use at your own risk. Other than that, have fun! More info: http://openexchangerates.org/terms/",
"license": "Data collected from various providers with public-facing APIs; copyright may apply; not for resale; no warranties given. Full license info: http://openexchangerates.org/license/",
"timestamp": 1339036116,
"base": "USD",
"rates": {
"EUR": 0.795767,
"GBP": 0.645895,
"JPY": 79.324997,
"USD": 1
}
}];
obj[0].rates.EUR; // output: 0.795767
or
obj[0].rates['EUR']; output: //0.795767
DEMO
If you want to isolate rates in another variable and use that variable then try like following:
var rates = obj[0].rates;
Now,
rates.EUR;
rates.GBP;
and so on.
You can also use JSON.parse() function of Javascript to convert JSON String into Javascript JSON object.
var JSONObject = JSON.parse("{'value1' : 1, 'value2' : 2}");
console.log(JSONObject.value1); // Prints '1'..
There are two ways to access properties of objects:
var obj = {a: 'foo', b: 'bar'};
obj.a //foo
obj['b'] //bar
Or, if you need to dynamically do it:
var key = 'b';
obj[key] //bar
If you don't already have it as an object, you'll need to convert it.
For a more complex example, let's assume you have an array of objects that represent users:
var users = [{name: 'Corbin', age: 20, favoriteFoods: ['ice cream', 'pizza']},
{name: 'John', age: 25, favoriteFoods: ['ice cream', 'skittle']}];
To access the age property of the second user, you would use users[1].age. To access the second "favoriteFood" of the first user, you'd use users[0].favoriteFoods[2].
Another example: obj[2].key[3]["some key"]
That would access the 3rd element of an array named 2. Then, it would access 'key' in that array, go to the third element of that, and then access the property name some key.
As Amadan noted, it might be worth also discussing how to loop over different structures.
To loop over an array, you can use a simple for loop:
var arr = ['a', 'b', 'c'],
i;
for (i = 0; i < arr.length; ++i) {
console.log(arr[i]);
}
To loop over an object is a bit more complicated. In the case that you're absolutely positive that the object is a plain object, you can use a plain for (x in obj) { } loop, but it's a lot safer to add in a hasOwnProperty check. This is necessary in situations where you cannot verify that the object does not have inherited properties. (It also future proofs the code a bit.)
var user = {name: 'Corbin', age: 20, location: 'USA'},
key;
for (key in user) {
if (user.hasOwnProperty(key)) {
console.log(key + " = " + user[key]);
}
}
(Note that I've assumed whatever JS implementation you're using has console.log. If not, you could use alert or some kind of DOM manipulation instead.)
Try the JSON Parser by Douglas Crockford at github. You can then simply create a JSON object out of your String variable as shown below:
var JSONText = '{"c":{"a":[{"name":"cable - black","value":2},{"name":"case","value":2}]},"o":{"v":[{"name":"over the ear headphones - white/purple","value":1}]},"l":{"e":[{"name":"lens cleaner","value":1}]},"h":{"d":[{"name":"hdmi cable","value":1},{"name":"hdtv essentials (hdtv cable setup)","value":1},{"name":"hd dvd \u0026 blue-ray disc lens cleaner","value":1}]}'
var JSONObject = JSON.parse(JSONText);
var c = JSONObject["c"];
var o = JSONObject["o"];