JSON using parse or stringify correctly [duplicate] - javascript

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.

Related

How to parsing the correct values from a json decoding [duplicate]

This question already has an answer here:
PHP or JavaScript issue when parsing JSON encoded PHP array into JavaScripts JSON.parse()
(1 answer)
Closed 1 year ago.
Hii ha ve written this question because i have a json converted to a string with a function of php called json_encode()
Something like this:
{ "data":"2","state":"false"}
when the original json that im trying to encode is like this:
{ "data":2,"state":false}
(Please note that the type of the variables are different, in the original i have an int number called data and boolean called state, but when i use json_encode() every variable goes to a string..)
The problem is when i try to json.PARSE() the value from the json encode of php in angular i don´t get the correct value, every variable is a string...
For example, isntead of getting the boolean state of the variable, i get "false" or "true", and this is a problem...
There is a way to parse this avoiding this problem? basically my problem is when i parse the json in my angular project i dont get the correct type of variable..
Thanks!
You can use JSON.parse on an individual value to convert it into the desired type:
const oldValue = JSON.parse('{"data":"2","state":"false"}')
const result = {}
Object.keys(oldValue).forEach(key => {
result[key] = JSON.parse(oldValue[key]);
});
Here's the other way around:
const oldValue = JSON.parse('{"data": 2,"state": false}');
const result = {}
Object.keys(oldValue).forEach(key => {
result[key] = oldValue[key].toString();
});
Note: These examples assume flat objects. You'd need to recurse through the object's tree if some of the values are objects, for example {a: {b: "c"}}.

javascript- How to parse JSON using javascript [duplicate]

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]);
});

Accessing an object from a JSON array of objects yields "Undefined" [duplicate]

This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 6 years ago.
I'm using a Blockspring API that returns a JSON array of objects (read in from a Google Sheet). However, whenever I try to access an object from the array, an "undefined" value is returned. I have attached the code and the console log below. Does anyone have any ideas why?
blockspring.runParsed("query-public-google-spreadsheet", { "query": "SELECT A, B, C", "url":
"https://docs.google.com/spreadsheets/d/1ZYvcYf_41aghdXRSpg25TKW4Qj9p1Lpz92b1xG-9R1Q/edit?usp=sharing"},
{ "api_key": "br_50064_1fe91fe1478ef990dc8b5e9b4041c2c476670306" }, function(res){
var obj=res.params;
console.log(obj);
var temp=obj[0];
console.log(temp);
}
You need to use obj.data[0] to access the first element of an array.
Looking at your output in the console, it seems you are missing the data property of obj.
Object obj doesn't have a property with name 0 so it returns undefined.
I would need to play around with it myself but I can tell that the problem is just how you are accessing the info.
When you try to grab the data with var temp=obj[0] you are treating object like an array when is it not. I would recommend trying to grab the data using this:
//get the actual array
JSONArray theArray = obj.getJSONArray("data"); //I believe it is stored in an array called data... could be that the obj is just fine
// now get the first element:
JSONObject firstItem = theArray.getJSONObject(0);
// and so on
String name = firstItem.getString("Name"); // A
You most likely can grab it using var temp = obj.data[0];

Deserializing Json Object in java [duplicate]

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);

Javascript JSON Array [duplicate]

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.

Categories

Resources