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 OverflowVideos
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);
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);
//By using jquery json parser
var obj = $.parseJSON('{"name": "", "skills": "", "jobtitel": "Entwickler", "res_linkedin": "GwebSearch"}');
alert(obj['jobtitel']);
//By using javasript json parser
var t = JSON.parse('{"name": "", "skills": "", "jobtitel": "Entwickler", "res_linkedin": "GwebSearch"}');
alert(t['jobtitel'])
Check this jsfiddle
As of jQuery 3.0, $.parseJSON is deprecated. To parse JSON strings use the native JSON.parse method instead.
Source: http://api.jquery.com/jquery.parsejson/
you have parse that Json string using JSON.parse()
..
}).done(function(data){
obj = JSON.parse(data);
alert(obj.jobtitel);
});
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.
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);
}
})();
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;
}
}
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"];