This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 5 years ago.
If my json is this:
[
["cat1"],
["cat2"],
["cat3"],
["cat4"],
["cat5"]
]
How to parse this in javascript. I am looking for some for loop kind of solution which can iterate over the json and can give me "cat1 ", "cat2" etc.
P.S.: My json list is dynamic which i am getting from some source. So, i dont know how my json elements are there and what are the fields.
Most browsers support JSON.parse(), which is defined in ECMA-262 5th Edition (the specification that JS is based on). Its usage is simple:
var json = '{"result":true,"count":1}',
obj = JSON.parse(json);
alert(obj.count);
For the browsers that don't you can implement it using json2.js.
As noted in the comments, if you're already using jQuery, there is a $.parseJSON function that maps to JSON.parse if available or a form of eval in older browsers. However, this performs additional, unnecessary checks that are also performed by JSON.parse, so for the best all round performance I'd recommend using it like so:
var json = '{"result":true,"count":1}',
obj = JSON && JSON.parse(json) || $.parseJSON(json);
This will ensure you use native JSON.parse immediately, rather than having jQuery perform sanity checks on the string before passing it to the native parsing function.
try this.
var list= [
["cat1"],
["cat2"],
["cat3"],
["cat4"],
["cat5"]
];
list.forEach(function(item){
console.log(item[0]);
});
Related
This question already has answers here:
How to parse JSON in Java
(36 answers)
Closed 6 years ago.
I cannot figure it out, I should deserialize a json object of this type:
{
"value":integer",
"total":1",
"records":138",
"rows":[
{
"value1":6,
"value2":true,
"bool":true,
"floatNumber":140.41",
"floatNumber2":28.7",
"floatNumber3":140.41",
"cssClassName":""",
"date":"19/03/2022"",
"UTCdate":"2016-03-22T00:00:00+0000"",
"UTCdate2":"2016-03-24T20:45:25+0000"
},
{
"value1":6,
"value2":true,
"bool":true,
"floatNumber":140.41",
"floatNumber2":28.7",
"floatNumber3":140.41",
"cssClassName":""",
"date":"19/03/2022"",
"UTCdate":"2016-03-22T00:00:00+0000"",
"UTCdate2":"2016-03-24T20:45:25+0000"}
]}
but I do not know how to do. I wish that this item was added to my class, pointing to what value to assign the corresponding property.
I tried to use Flexjson library but didn't saw any function that will let me what i want to do.
Where to start?
PS: I never serialized an object to JSON, so I do not know how it works.
You can go through this tutorial. Hope it will help you.
How to convert Java object to / from JSON (Jackson)
https://dzone.com/articles/deserializing-json-java-object
That's json. You need to parse it using api.
For example
{'profiles': [{'name':'john', 'age': 44}, {'name':'Alex','age':11}]}
you will have to do something of this effect:
JSONObject myjson = new JSONObject(the_json);
JSONArray the_json_array = myjson.getJSONArray("profiles");
this returns the array object.
Then iterating will be as follows:
int size = the_json_array.length();
ArrayList<JSONObject> arrays = new ArrayList<JSONObject>();
for (int i = 0; i < size; i++) {
JSONObject another_json_object = the_json_array.getJSONObject(i);
//Blah blah blah...
arrays.add(another_json_object);
}
//Finally
JSONObject[] jsons = new JSONObject[arrays.size()];
arrays.toArray(jsons);
Example code is taken from How to parse a JSON and turn its values into an Array?
Java or Javascript? You do know that these are 2 completely different languages?
In Javascript you do it like this:
// object to string:
JSON.stringify(object);
// string to object
JSON.parse(object);
I have the following javascript object, in an array. I am using PHP's json_encode to get this value
[ { January=100}, { February=100} ]
I am trying to convert the following objects to
["January",100],["February",100]
I have searched around a lot and couldn't find an answer.
Any help would be really appreciated. Thanks!
Assuming you're trying to do this in Javascript, it can be done very easily using a library like Lodash:
server_array.map(_.toPairs)
Using native Javascript map function, with lodash's toPairs
Ignoring the incorrect syntax of your example javascript object code...
This is how to convert a javascript object to an array:
var newArray = []
for (var i in yourObject)
if(yourObject.hasOwnProperty(i))
newArray.push([i,yourObject[i]])
The above will yield the results your looking for.
This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 8 years ago.
This is what I'm getting from server
['model':{"category":[{"id":1}],"food":[{"id":1}].... // long json here
How can I use jquery/javascript to parse to get category id and food id? I tried to use
JSON.parse(data)
or
JSON.stringify(data)
And after that, doing
$.each(data, function (i, x) {
it will give me each letter of all array. How can I parse it correctly, getting the ids that I want?
JSON.parse(data) will turn the data you showing into a JavaScript object, and there are a TON of ways to use the data from there. Example:
var parsedData = JSON.parse(data),
obj = {};
for(var key in parsedData['model']){
obj[key] = parsedData['model'][key]['id'];
}
Which would give you a resulting object of this:
{category:1, food:1}
This is based on the limited example of JSON you provided, the way you access it is entirely dependent on its structure. Hopefully this helps get you started, though.
You want to use JSON.parse(), but it returns the parsed object, so use it thusly:
var parsed = JSON.parse(data);
then work with parsed.
This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 8 years ago.
I am using a get request from a server API and I am making a request and then doing this:
var resp = JSON.parse(response);
I call to the server providing 0001 & 0002 as arguments and
after the JSON.parse it returns an array such as:
{"0001":{"id":1},"0002":{"id":2}}
I know that traditionally if i were given static responses such as
{"placeID":{"id":1},"placeID":{"id":2}}
I could do this:
resp.placeId.id
but given that the return names aren't always the same how can I access that first value resp.0001.id given that 0001 may not always be the value returned?
Use a for...in loop.
for(var property in resp) {
console.log(property + ": " + resp[property]);
}
You can access the "0001" element of the response like this:
resp["0001"].id
Since you say that you're providing the id in the query, you presumably have it stored in a variable somewhere.
If you really want to access the first element in the response, you can't use JSON.parse, because you'll lose the ordering information once you suck that data into an object. And if you have to care about the order of the elements, then that JSON is badly-formed, and should be using an array instead of a top-level object.
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Chrome and probably Opera sort object properties automatically
I have a very simple code:
var obj = {3:'a',2:'b',1:'c'};
console.log(obj);
In Firefox 4.0.1 it returns:
Object { 3="a", 2="b", 1="c"}
In Chrome 11.0.696.71 it returns:
Object { 1="c", 2="b", 3="a"}
How can I coerce Chrome doesn't sort this object?
For Objects the spec is that the order of elements is not preserved. In other words javascript doesn't guarantee any particular order for the properties of an Object.
You'll have to use an array if you want to preserve the order of elements. In this case, your Object can be rewritten to:
var arrobj = ['c','b','a'];
or
var arrobj = ['a','b','c'].reverse();
Where you have take into account that the first element index will be 0 (zero)
It's a known "bug"/feature of chrome. Even author of jQuery indignant of this, but chrome guys stay inflexible, saying that this is a "feature":
http://code.google.com/p/chromium/issues/detail?id=883 [1]
As a workaround use arrays or some kind of MixedCollection (as in extjs) or something similar.
null !== true and also null !== false // in php and js it's so
[1]: John Resig (jeresig) is an author of jquery