json stringify with variables - javascript

I am using JSON stringify, here is my code:
var lista={};
for(var i=0; i < arr.length; i++){
lista[i]=[];
//lista[i].push('imagen:'+arr[i].id);
lista[i].push('nick:'+arr[i].nick);
lista[i].push('tlfno:'+arr[i].tlfno);
lista[i].push('nombre:'+arr[i].nombre);
lista[i].push('descripcion:'+arr[i].descripcion);
lista[i].push('direccion:'+arr[i].direccion);
lista[i].push('fecha:'+arr[i].fecha);
lista[i].push('estado:'+arr[i].estado);
lista[i].push('tipoimagen:'+arr[i].tipoimagen);
//lista[i].push('imagen:'+arr[i].imagen);
}
var json = JSON.stringify(lista);
console.log(json);
I am getting this output:
{"0":["nick:pepe","tlfno:678909897","nombre:dsfdfsf","descripcion:dsdsdsd","direccion:fdfdf","fecha:fdfdf","estado:1","tipoimagen:image/jpeg"]
but is wrong because it would be like this:
{"0":["nick":"pepe" with double quotes, somebody knows how to show this double quote? Thanks

I'm guessing you're trying to push objects into that array, not strings
lista[i].push( {nick: arr[i].nick} );
That would give you something like
{"0":[{"nick":"pepe"}]}
note that {"0":["nick":"pepe"... is not valid, so you won't be getting that
FIDDLE

Related

Retrieving data from an object

I have an object which looks like this.
{
"class_details":{
"class_1":{student_4":"<name>","student_3":"<name>,student_2":"<name>","student_1":"<name>},
"class_2":{"student_1":"<name>},
"class_0":{student_2":"<name>","student_1":"<name>
}
}
I am trying to use a loop to iterate over the classes but I am not able find a perfect way to do it.
I cant do something like this,
for(int i=0; i < $scope.rounds.class_details.length;i++)
console.log($scope.rounds.class_details.round_[i])
So i am doing this
for(int i=0; i < $scope.rounds.class_details.length;i++)
console.log(Object.keys($scope.rounds.class_details)[i])
But here the class details do not come in an order and this matters in my case.
It would be great if there is an alternative similar to
for(int i=0; i < $scope.rounds.class_details.length;i++)
console.log($scope.rounds.class_details.round_[i])
or if there is a simple way to sort the JSON class details.
To get the keys in ascending order do:
var class_details_keys = Object.keys($scope.rounds.class_details);
class_details_keys = class_details_keys.sort(function(a,b) {return (+a.substring(6)) - (+b.substring(6));});
for(int i=0, length = class_details_keys ; i < length;i++)
console.log($scope.rounds.class_details[class_details_keys[i]]);
This will return your classes in ascending order by taking the substring after 'class_' and ordering them. You can't do a simple string comparison since "4" > "10" will return incorrect result.
The simplest way to read data like you're hoping is the following:-
for(int i=0; i < $scope.rounds.class_details.length;i++)
console.log($scope.rounds.class_details["round_" + i]);
This is because you can access an objects property in two ways: -
Allows you to pass a dynamic value in (i.e. the i value)
object["property" + withVariable + "Name"]
Simple, readable way where you know the property.
object.propertyName
First, fix json. NOTE: there are some quotes missing in the original code.
"class_details":{
"class_1":{
"student_4":"<name>",
"student_3":"<name>",
"student_2":"<name>",
"student_1":"<name>"
},
"class_2":{
"student_1":"<name>"
},
"class_0":{
"student_2":"<name>",
"student_1":"<name>"
}
}
Followed to this:
//parse to json. Assume the
//'body' is the json data received
//if there is data in body
if(body){
//parse body
var parsed_body= JSON.parse(body);
//your data
var class_details = parsed_body.class_details;
var class_2_student_1 = parsed_body.class_details.class_2.student_1;
//if you want to print json directly to the front-end,
//then Object Object may be printed out. to prevent this,
//one could use .toString() to convert Object to String.
}
else{}//do something if no data in the body

how to parse json array

I'm trying to parse something like this
{
"popular result":[
{"term":"Summer","url":"http://summer.com"},
{"term":"Autumn","url":"http://autumn.com"},
{"term":"spring","url":"http://spring.com/"},
{"term":"winter","url":"http://winter.com/"}]
}
<script type="text/javascript">
$(document).ready(function () {
$.getJSON('/Controls/GetPopularSearches', function (json) {
for (var i = 0; i < json.length; i++) {
$.each(myJson.i, function (key, value) {
alert(value.term);
});​
}
});
});
</script>
but nothing happened! Because is array in array! Please let me know how to do this
Arrays and objects are different things. You will want to investigate them tons more before things get really challenging.
Assuming json really does equal the object you provide (in JSON those show up as {}), then json['popular result'] (you could use a . if there wasn't a space) is the array (in JSON those show up at []) you want to traverse.
For some reason, this confusion got you looping over an object (not going to get you anywhere as length is rarely defined for it) and then (ignoring the typo on myJson), you started looping over something that didn't exist (which didn't crash b/c it never got there).
Cleaning it up...
<script type="text/javascript">
$(document).ready(function () {
$.getJSON('/Controls/GetPopularSearches', function (json) {
for (var i=0;i<json['popular result'].length;i++) {
alert(json['popular result'][i].term + ' points to the URL ' + json['popular result'][i].url);
}
});
});
</script>
Notice how the alert references the json object (that's your variable name), the popular result array, then [i] is the "row" in that array, and the term/url element of the object on that row.
NOTE: Running something with a ton of alerts as you're debugging is annoying. Check out console.log.
You don't need $.each and you need to loop over the array set as the value of popular result which is inside a containing object.
$.getJSON('/Controls/GetPopularSearches', function (json) {
var arr = json['popular result'];
for (var i = 0, l = arr.length; i < l; i++) {
console.log(arr[i].term);
}
});
Demo.
Check this fiddle
var jsontext =
'{"popularresult":[{"term":"Summer","url":"http://summer.com"},{"term":"Summer","url":"http://summer.com"}]}';
var getContact = JSON.parse(jsontext);
for (i = 0; i < getContact.popularresult.length; i++) {
alert(getContact.popularresult[i].term);
}
http://jsfiddle.net/ae8gd/
If you get the jsonObject as shown then
var JsonArray=json.popular; //get jsonArry
$.each(JsonArray,function(i,val){
// do logic
});
To parse json use JSON.parse();

Uncaught TypeError: Cannot read property 'length' of undefined for simple JSON array

I am calling a function this way .
var responseinner = returnvalues(selectedeleemnt);
console.log(responseinner);
displaying as Object
console.log(JSON.stringify(responseinner));
displaying as [{"name":"Coke","image":"json_images/coke_can.jpg","type":["250ml","300ml"],"price":["50","60"]}]
I tried all the ways of parsing this value
[{"name":"Coke","image":"json_images/coke_can.jpg","type":["250ml","300ml"],"price":["50","60"]}]
But always it throws the error as
Uncaught TypeError: Cannot read property 'length' of undefined
I used JSON.parse , JSON.stringfy() . but none helped .
for (var i = 0; i < responseinner.type.length; i++) {
}
could anybody please help me
for(var i=0;i<responseinner.length;i++){
responseinner[i].type .... }
Your responseinner isn't an Object but an Array with only one element.
So, you'll have to use responseinner[0].type.length
If it was an object, it would have started with {} and not [], with what arrays start.
You can use of
for (let element of responseinner) {
// do something../
console.log(element.name)
}
To parse json with jquery:
$.each($.parseJSON(responseinner), function(key,value){
//do something
});
If responseinner is already formed as a json you don't need the $.parseJSON
or
responseineer[0].name
responseineer[0].image
...
Json data comes into an array so get it's object with an index, so to access it: responseineer[0]
try test[0].type.length you have an Object in an array of length 1 therefore you must first define the index location of the Object in the array which is trivial since the array has 1 defined index.
for (var i = 0; i < responseinner[0].type.length; i++) {
}
for(var i=0;i
Its works fine but...how to assign to gridview in client side

JSON rows Extracting issue in JavaScript

I have following json data coming from server in which i want to extract LimitClass and LimitClassID and store their values in respective arrays.
{
"ErrorDesc":"",
"ErrorCode":"",
"LimitClassList":"[{\"LimitClass\":\"L16\\n\",\"LimitClassId\":\"32900\\n\"},{\"LimitClass\":\"28febL0\\n\",\"LimitClassId\":\"31901\\n\"},{\"LimitClass\":\"L14\\n\",\"LimitClassId\":\"31900\\n\"},{\"LimitClass\":\"L17\\n\",\"LimitClassId\":\"32950\\n\"},{\"LimitClass\":\"L15\\n\",\"LimitClassId\":\"31950\\n\"},{\"LimitClass\":\"L0\\n\",\"LimitClassId\":\"21901\\n\"},{\"LimitClass\":\"L4\\n\",\"LimitClassId\":\"23000\\n\"},{\"LimitClass\":\"OTC Send\\n\",\"LimitClassId\":\"30901\\n\"},{\"LimitClass\":\"L2\\n\",\"LimitClassId\":\"22900\\n\"},{\"LimitClass\":\"L12\\n\",\"LimitClassId\":\"28900\\n\"},{\"LimitClass\":\"L6\\n\",\"LimitClassId\":\"23900\\n\"},{\"LimitClass\":\"L1\\n\",\"LimitClassId\":\"25900\\n\"},{\"LimitClass\":\"L13\\n\",\"LimitClassId\":\"29900\\n\"},{\"LimitClass\":\"L7\\n\",\"LimitClassId\":\"24900\\n\"},{\"LimitClass\":\"L8\\n\",\"LimitClassId\":\"26900\\n\"},{\"LimitClass\":\"L10\\n\",\"LimitClassId\":\"27900\\n\"},{\"LimitClass\":\"L13\\n\",\"LimitClassId\":\"30900\\n\"},{\"LimitClass\":\"UatTesting123\\n\",\"LimitClassId\":\"32901\\n\"}]"
}
Here is the code I have tried :
var list = data.LimitClassList;
var arrayLimitClass = [];
var arrayLimitClassId = [];
for(var i in list) {
arrayLimitClass.push(list[i].LimitClass);
arrayLimitClassId.push( list[i].LimitClassId);
}
alert(list);
alert(arrayLimitClass);
alert(arrayLimitClassId);
List variable has following result when I alert it:
[{\"LimitClass\":\"L16\\n\",\"LimitClassId\":\"32900\\n\"},{\"LimitClass\":\"28febL0\\n\",\"LimitClassId\":\"31901\\n\"},{\"LimitClass\":\"L14\\n\",\"LimitClassId\":\"31900\\n\"},{\"LimitClass\":\"L17\\n\",\"LimitClassId\":\"32950\\n\"},{\"LimitClass\":\"L15\\n\",\"LimitClassId\":\"31950\\n\"},{\"LimitClass\":\"L0\\n\",\"LimitClassId\":\"21901\\n\"},{\"LimitClass\":\"L4\\n\",\"LimitClassId\":\"23000\\n\"},{\"LimitClass\":\"OTC Send\\n\",\"LimitClassId\":\"30901\\n\"},{\"LimitClass\":\"L2\\n\",\"LimitClassId\":\"22900\\n\"},{\"LimitClass\":\"L12\\n\",\"LimitClassId\":\"28900\\n\"},{\"LimitClass\":\"L6\\n\",\"LimitClassId\":\"23900\\n\"},{\"LimitClass\":\"L1\\n\",\"LimitClassId\":\"25900\\n\"},{\"LimitClass\":\"L13\\n\",\"LimitClassId\":\"29900\\n\"},{\"LimitClass\":\"L7\\n\",\"LimitClassId\":\"24900\\n\"},{\"LimitClass\":\"L8\\n\",\"LimitClassId\":\"26900\\n\"},{\"LimitClass\":\"L10\\n\",\"LimitClassId\":\"27900\\n\"},{\"LimitClass\":\"L13\\n\",\"LimitClassId\":\"30900\\n\"},{\"LimitClass\":\"UatTesting123\\n\",\"LimitClassId\":\"32901\\n\"}]
But I am getting dots (.) when I alert arrayLimitClass and arrayLimitClassId. What am I doing wrong in extracting rows of json Object?
"LimitClassList":"[{\"LimitClass\":\"L1....]"
^ ^
LimitClassList is a string, not an array. Make it so it is an actual array, than your code should work. There should be no reason to have to parse it again.
The value below data.LimitClassList is itself a String containing JSON. You have to decode this first.
var list = JSON.parse( data.LimitClassList );
var arrayLimitClass = [];
var arrayLimitClassId = [];
// ...
This is more or less a workaround. You should have a look at your server code and fix the encoding error there!

How to convert a json formatted string into a json array in javascript

I am using the $.post() method to retrieve a json formatted string which looks like this:
{elementid:10},{elementid:11},{elementid:12},{elementid:14},{elementid:15}
In the success callback function of $.post(), I would like to loop the values of this json formatted string but I can't figure out how to do it.
// data returns {elementid:10},{elementid:11},{elementid:12},{elementid:14}, etc.
$.post('form.php',
{'postvalues' : input_ids},
function(data){
var elements = Array();
elements = [data];
for(var i=0; i<elements.length; i++) {
var value = elements[i]['elementid'];
alert('value = '+value);
}
});
When I do this, instead of getting value = 10, value = 11, value = 12, etc. in the alert box,
I get value = undefined
What must I change in the format of the variable 'data' so that it will be interpreted as array values and not a string?
thanks for your help
Your string isn't valid JSON if you don't have the '[' and ']' characters.
You can add those in , then parse it using the jQuery.parseJSON()[docs] method.
elements = jQuery.parseJSON( '[' + data + ']' );
...but it would be better if you sent correct JSON data from the server.
Also, your JSON keys must be wrapped in double quotes.
{"elementid":10},{"elementid":11},{"elementid":12},{"elementid":14},{"elementid":15}
Your query isn't returning valid JSON. It should be [{"elementid":10},{"elementid":11},{"elementid":12},{"elementid":14},{"elementid":15}] and not {elementid:10},{elementid:11},{elementid:12},{elementid:14},{elementid:15}. Is there any way you can fix that? Otherwise, you will have to do this:
elements = jQuery.parseJSON("[" + data + "]");
The right thing to do, however, is to return valid JSON from the server (if you have any control over that).
use JSON.parse(data) to put a string which contains a JSON object in a variable
Try this, it looks like you are getting passed an array (apart from the missing surrounding []), and if you tell jquery that it's json it'll parse it for you properly:
$.post('form.php', {'postvalues' : input_ids}, function(data){
for(var i=0; i<data.length; i++) {
var value = data[i]['elementid'];
alert('value = '+value);
}
}, 'json'); // telling it that the content received is json
Use the "for in" statement. Such as:
for (var x in data) {
console.log(data[x]['elementid']);
}
I tested it and it perfectly worked!
Hope this helps.
Ps. Console.log() output the result in the browser console (so it won't work in IE, of course).

Categories