Get JSON data after it's stored in a variable - javascript

After getting JSON back from the ajax call, the data "response" is stored in the "theObj" variable; however, when I try to log "theObj" to the console, it results in multiple "[Object object]", even with JSON.stringify().
If I do a "theObj[0]" (response.results[0] works fine), I get "[", for the first character in "[Object object]".
Q: How can I store JSON in a variable and get the data back out afterward?
$.ajax(settings).done(function(response) {
for (var i = 0; i < 19; i++) {
//creating JSONenter[enter image description here][1]
theObj += response.results[i];
if (i == 18) {
//console.log(theObj.id)
console.log(JSON.stringify(theObj[0].id))
}
}
}

I think the error is in the line
theObj += response.results[i];
So try this instead
function (response) {
var list = response.results;
// if there is no reason for having 19, replace this with var end = list.length
var end = Math.min(list.length, 19);
for(var index = 0; index < end; index++) {
theObj.push(list[index]);
}
console.log(theObj);
}
We don't see the initialization of theObj variable
If it is an array you should use the push function to add elements to it
If it is a common object then use theObj[id] = list[index];
DISCOURAGED If it is a string then you should use theObj += JSON.stringify(response.results[i];) + ", ";, then make sure that you add } or ] at the end if it is an object or array respectively (and that it has also has { or [ in the begining) and then use JSON.parse(theObj) to convert it back to an object
Please let me know which of the above are you using

try this
$.ajax(settings).done(function(response) {
$.each( response, function( key, val ) {
console.log(val.id)
});
}

I assumed you want to get the data as object and not a string.
For that you have to use var object = JSON.parse(yourJSONString). This method returns an object based on your JSON string.
Example:
JSON result:
{
"name":"John Doe"
}
Javascript code:
var john = JSON.parse(result);
console.log(john.name); //prints John Doe

Related

Am I building the JavaScript objects correctly for a JSON string array?

In JavaScript I have the following code:
for (i = 1; i<3; i++)
{
// above I collect check_a and check_b through radio button responses.
var connectJSON = ",";
var passObj = {id:i, ask:check_a, description:check_b};
// adding object string together in tempObj
var tempObj = tempObj + connectJSON + passObj;
}
// get ready for transport to server and display result of string
var data = JSON.stringify(tempObj);
console.info("info: " + data);
// post string to server
$.ajax
({
type: 'POST',
url: 'out.php',
data: {data: data},
success: function(msg)
{
alert(msg);
}
});
In out.php I try to determine the result back from the server. The code is as follows:
<?php
if (ISSET($_POST['data']))
{
echo "TRUE";
}
ELSE
{
echo "False";
}
var_dump($_POST['data']);
?>
I am getting this message, AJAX alert (msg) :
**True** string(42) ""question, [object Object], [object Object]""
Apparently this message is describing the string array being passed.
What I now need to do, if the format is correct, is to be able to access the string array - maybe with JSON_decode and identify properties of the array so that I can make insertions into a MySQL database.
Thanks for any AND all help...
var connectJSON = ",";
var passObj = {id:i, ask:check_a, description:check_b};
// adding object string together in tempObj
var tempObj = tempObj + connectJSON + passObj;
First of all. If you just test this part in the console you will see that if you concatenate JS object and the string ',' you get the string "[object Object],[object Object]". You need to first stringify the JS object before concatenating it with strings.
Second I can really seem to understand your code but looping that code will just override those variables because they are declared in the loop so that doesn't seem correct. Probably you want to get the declarations out of the loop.
Otherwise it's kind of like this - you stringify the Js object and pass it as data to the ajax.
No. To build JSON, first build a valid structure, then use JSON.stringify on the result; don't convert to string while building the structure. connectJSON + passObj will force passObj to string, resulting in "[object Object]".
Instead:
var array = []; // <== An empty array
for (i = 1; i<3; i++)
{
// Push entries into the array
array.push({id:i, ask:check_a, description:check_b});
}
// Convert to JSON
var data = JSON.stringify(array);
Side note: The code in your question didn't declare i anywhere. If your real code doesn't, it's falling prey to The Horror of Implicit Globals.* Be sure to declare your variables. :-)
* (that's a post on my anemic little blog)
The issue is here var tempObj = tempObj + connectJSON + passObj;. You are concatinating objects and strings. In that case JavaScript will use Object.prototype.toString() first and then do the concatination. and Object.prototype.toString() in case of objects will produce [object Object]. To fix this you have to create an array like below.
var tempObj = [];
for (i = 1; i < 3; i++) {
// above I collect check_a and check_b through radio button responses.
var connectJSON = ",";
var passObj = {
id: i,
ask: check_a,
description: check_b
};
tempObj.push(passObj);
}
Also, you can skip JSON.stringify() and directly submit the JS object.
I'm trying to understand how is this deceleration :
var tempObj = tempObj + etc...;
possible ?
you cant set the value of something you just declared,
to the same thing you just declared .

Get array from json using javascript

Server returns me such object, but i need only array ITEMS.
How can i get it?
I tried array['items'] but the result is undefiend
{
"items": [
{
..
},
{
..
},
{
..
}
],..
,..
}
// JSON string returned from the server
var text = '{"items":[{"name":"itemX" ,"price":15},{"name":"itemY","price":25},{"name":"itemZ","price":20}]}';
// Convert the string returned from the server into a JavaScript object.
var object = JSON.parse(text);
// Accessing a specific property value of an item
console.log(object.items[0].name); //itemX
// Extract 'items' in to a separate array
var itemsArray = object.items;
console.log(itemsArray); //[itemObject, itemObject, itemObject]
If you're getting this as a string:
var json = JSON.parse(my_json_string)
Then,
var keys = Object.keys(json);
var values = [];
for(var i = 0; i < keys.length; i++){
values.push(json[keys[i]]);
}

How to fetch data from JSON object in JavaScript?

I am working on SpringMVC. In my controller I create a JSON object and I pass that object to JavaScript. How can I read that object in JavaScript?
My Map object
Map<String rootNode,List<String>> map = new HashMap<String rootNode,List<String>();
String rootNode = "bhanu";
ArrayList<String> al = new ArrayList<String>();
for( int i = 0; i < UserProfile.size; i++ ) {
al.add( userProfile.get( i ) );
}
map.put( userProfile, al );
At last my Map object has this data:
{
"Bhanu":["hari#gmail.com","balu#gmail.com","santha#gmail.com"],
"root":["bhanu#gmail.com","anu#gmail.com","apar#gmail.com"],
"hari":["bhanuprasad#gmail.com","sravya#gmail.com","mahesh#gmail.com"],
"balu":["rama#gmail.com"]
}
Now I convert this object with GSon:
Gson gson = new GSon();
String orgChartUsers = gson.toJson(map);
Now I passed this string to JavaScript because this is my Ajax response:
function orgUsers( result ) {
var orgObject = JSON.parse( result );
for(var name in result) {
console.log(name + "=" + result[name]);
}
}
This is working fine but i want to fetch data like this
first i want to fetch data from "root" in root i have some data when i read root for example i got bhanu#gmail.com now i want to fetch the data from Bhanu here i got some data like hari#gmail.com again i want to fetch data for hari like this i want how can i do this any one help me
Your lists will become javascript arrays, so for example you could use:
window.alert (orgObject["Bhanu"][0]);
which should pop up "hari#gmail.com" given your example data.
See How to list the properties of a JavaScript object for details of how to list the keys of your map, should you need this.
The result will be either an object or array.
To iterate over objects you can use the for-in loop
for (var key in obj) {
if(obj.hasOwnProperty(key)) {
// do something here
}
}
To iterate over an array you can use a normal loop:
for (var i = 0, ilen = array.length; i < ilen; i += 1) {
// do something here
}
Here is the most simple way
var result = {"Bhanu":["hari#gmail.com","balu#gmail.com","santha#gmail.com"],"root":["bhanu#gmail.com","anu#gmail.com","apar#gmail.com"],"hari":["bhanuprasad#gmail.com","sravya#gmail.com","mahesh#gmail.com"],"balu":["rama#gmail.com"]};
for(var name in result) {
console.log(name + "=" + result[name]);
}
This outputs:
Bhanu=hari#gmail.com,balu#gmail.com,santha#gmail.com
root=bhanu#gmail.com,anu#gmail.com,apar#gmail.com
hari=bhanuprasad#gmail.com,sravya#gmail.com,mahesh#gmail.com
balu=rama#gmail.com
Have in mind that the arrays are actually cast to a string. So result[name] is actually an array.

Find specific key value in array of objects

This is the code:
var groups = {
"JSON":{
"ARRAY":[
{"id":"fq432v45","name":"Don't use me."},
{"id":"qb45657s","name":"Use me."}
]
}
}
I want to get the name value where the id is "qb45657s" how could this be accomplished? I figured the obvious loop through all of the array and check if it's equal but is there an easier way?
Edit: I cannot change "Array" to an object because I need to know the length of it for a different function.
You can simply filter on the given id:
groups["JSON"]["ARRAY"].filter(function(v){ return v["id"] == "qb45657s"; });
This will return [{"id":"qb45657s","name":"Use me."}]
Assuming you had a valid JSON string like this (note I say valid, because you need an enclosing {} or [] to make it valid):
var json = '{"JSON":{
"ARRAY":[
{"id":"fq432v45","name":"Don't use me."},
{"id":"qb45657s","name":"Use me."}
]
}
}';
You would just parse it into an actual object like this:
var jsonObj = JSON.parse(json); // makes string in actual object you can work with
var jsonArray = jsonObj.JSON.ARRAY; // gets array you are interested in
And then search for it like:
var needle = 'qb45657s';
var needleName;
for (var i = 0; i < jsonArray.length; i++) {
if (jsonArray[i].id === needle) {
needleName = jsonArray[i].name;
}
}

Replace Element in JSON with a element in a Javascript array

I have this JSON
[{"id":7,"serial":"7bc530","randomDouble":0.0,"randomDouble2":0.0,"randomDouble3":0.0,"date":1352228474000,"removed":null},
{"id":8,"serial":"4a18d27","randomDouble":0.0,"randomDouble2":0.0,"randomDouble3":0.0,"date":1352228474000,"removed":null},
{"id":9,"serial":"f30ef","randomDouble":0.0,"randomDouble2":0.0,"randomDouble3":0.0,"date":1352228474000,"removed":null},
{"id":10,"serial":"9e6d","randomDouble":0.0,"randomDouble2":0.0,"randomDouble3":0.0,"date":1352228474000,"removed":null},
{"id":11,"serial":"4d8665a3","randomDouble":0.0,"randomDouble2":0.0,"randomDouble3":0.0,"date":1352228474000,"removed":null},
{"id":12,"serial":"4fe1457","randomDouble":0.0,"randomDouble2":0.0,"randomDouble3":0.0,"date":1352228474000,"removed":null}]
and I have this JSON
{"computers":[{"id":"7bc530","name":"Dell","description":"Dell"},
{"id":"f30ef","name":"HP","description":"HP"},
{"id":"9e6d","name":"Compaq","description":"Compaq"},
{"id":"4d8665a3","name":"Toshiba","description":"Toshiba"},
{"id":"4fe1457","name":"Asus","description":"Asus"},
{"id":"4a18d27","name":"Acer","description":"Acer"}]}
I want to replace the "serial" element in the first JSON with the "Description" in this one. The reason why I need it in one JSON is that I am using a DataTable and I can only pass one JSON in.
I'm not sure how I can do this in Javascript / JQuery?
You can accomplish this without any jQuery by setting up small function:
(see the demo fiddle)
function replaceSerial (data1, data2) {
var descs = {}, computers = data2['computers'], final = data1;
for (var i = 0; i < computers.length; i++ ) {
descs[computers[i]['id']] = computers[i]['description'];
}
for (var i = 0; i < data1.length; i++) {
final[i]['serial'] = descs[data1[i]['serial']];
}
return final;
}
Then just save your two pieces of JSON into variables and invoke the function:
var json1, json2, mergedJson;
json1 = // DATA IN FIRST JSON;
json2 = // DATA IN SECOND JSON;
mergedJson = replaceSerial (json1, json2);
Assuming your first object is called to and the second object is called from
// Iterate over each entry in to
to.forEach(function(value) {
// In each iteration find elements in from where the id is the same
// as the serial of the current value of to
var description = from.computers.filter(function(element){
if (element.id == value.serial) return true;
});
// Copy description of first found object in the description property of
// the current object
value.description = description[0].description;
// Unset serial?
delete value.serial;
});
DEMO

Categories