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]);
}
Answer from Anand on Stack OverflowJSON 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;
}
}
jquery - How can I get the key name and its value from an array within a JSON object - Stack Overflow
Obtaining key, value from $.each - json OBJECT; NOT array
Extract specific values from key/value
javascript - Loop and get key/value pair for JSON array using jQuery - Stack Overflow
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"];
Just use this code, it will work. I just changed some content of your code, try this::
var json_data = {"themenu":[
{
"stuff": "stuffs",
"pages": [
{"name1": "page111"},
{"name2": "page222"},
{"name3": "page333"}
]
}
]};
$(document).ready(function() {
// $.getJSON(json_data, function(data) {
$(json_data.themenu).each(function() {
var stuff = this.stuff;
alert(stuff); // alerts 'stuffs'
$(this.pages).each(function(key, value) {
$.each(this, function(key, value) {
var pageName = key;
var pageUrl = value;
alert(pageName + ' ' + pageUrl);
});
});
});
// })
});
Assuming var json_data having your data, Replace it as you need.
When looping your JSON and using this.key/this.value you literally search for key key/value (if it would be {'key': ..., 'value': ...}.
Your $.each(this.pages, function (key, value) gives you array of your desired value. You can loop once more to get key/value as text:
var json = {
"pages": [{
"name1": "page111"
}, {
"name2": "page222"
}, {
"name3": "page333"
}]
};
$.each(json.pages, function(k, v) {
console.log(k, v);
$.each(this, function(key, value) {
console.log('->', key, value);
//alert(keyName + ' ' + value);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
You have a string representing a JSON serialized JavaScript object. You need to deserialize it back to a JavaScript object before being able to loop through its properties. Otherwise you will be looping through each individual character of this string.
var resultJSON = '{"FirstName":"John","LastName":"Doe","Email":"[email protected]","Phone":"123 dead drive"}';
var result = $.parseJSON(resultJSON);
$.each(result, function(k, v) {
//display the key and value pair
alert(k + ' is ' + v);
});
Live demo.
var obj = $.parseJSON(result);
for (var prop in obj) {
alert(prop + " is " + obj[prop]);
}
//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 can use jQuery's .grep().
var newArray = $.grep(obj, function(item){ return item.name == "Math"; });
If you need to do multiply query against this array, I suggest you using the following code to convert the array to a json object:
var newObj = yourArray.reduce(function(previousValue, currentValue, index, array) {
return previousValue[currentValue.name] = currentValue;
}, {});
You will get:
{"Math":{"name": "Math", unit: "3"}, "Physics":{"name": "Physics", unit: "3"}, ...}
You only loop once but you can reuse it later.
var jsonData = [{"person":"me","age":"30"},{"person":"you","age":"25"}];
for(var i in jsonData){
var key = i;
var val = jsonData[i];
for(var j in val){
var sub_key = j;
var sub_val = val[j];
console.log(sub_key);
}
}
EDIT
var jsonObj = {"person":"me","age":"30"};
Object.keys(jsonObj); // returns ["person", "age"]
Object has a property keys, returns an Array of keys from that Object
Chrome, FF & Safari supports Object.keys
[What you have is just an object, not a "json-object". JSON is a textual notation. What you've quoted is JavaScript code using an array initializer and an object initializer (aka, "object literal syntax").]
If you can rely on having ECMAScript5 features available, you can use the Object.keys function to get an array of the keys (property names) in an object. All modern browsers have Object.keys (including IE9+).
Object.keys(jsonData).forEach(function(key) {
var value = jsonData[key];
// ...
});
The rest of this answer was written in 2011. In today's world, A) You don't need to polyfill this unless you need to support IE8 or earlier (!), and B) If you did, you wouldn't do it with a one-off you wrote yourself or grabbed from an SO answer (and probably shouldn't have in 2011, either). You'd use a curated polyfill, possibly from es5-shim or via a transpiler like Babel that can be configured to include polyfills (which may come from es5-shim).
Here's the rest of the answer from 2011:
Note that older browsers won't have it. If not, this is one of the ones you can supply yourself:
if (typeof Object.keys !== "function") {
(function() {
var hasOwn = Object.prototype.hasOwnProperty;
Object.keys = Object_keys;
function Object_keys(obj) {
var keys = [], name;
for (name in obj) {
if (hasOwn.call(obj, name)) {
keys.push(name);
}
}
return keys;
}
})();
}
That uses a for..in loop (more info here) to loop through all of the property names the object has, and uses Object.prototype.hasOwnProperty to check that the property is owned directly by the object rather than being inherited.
(I could have done it without the self-executing function, but I prefer my functions to have names, and to be compatible with IE you can't use named function expressions [well, not without great care]. So the self-executing function is there to avoid having the function declaration create a global symbol.)
I hope.. It should do the trick
var inputString=[{"rKVAH_Lag":"xyz","Asset_Name":"GSM Meter"}];
var keys=[]
var values=[]
i=0
for (var key in inputString[0]) {
keys[i]=key;
values[i]=inputString[0][key]
i=i+1
}
console.log(keys);
console.log(values);
Maybe this works for you.
var obj = { a: 1, b: 2, c: 3, d: 4, e: 5 },
keys = Object.keys(obj),
values = keys.map(function (k) { return obj[k]; });
document.write('<pre>' + JSON.stringify(keys, 0, 4) + '</pre>');
document.write('<pre>' + JSON.stringify(values, 0, 4) + '</pre>');