building a JSON string - javascript

I have a two part question (Very new to JSON)
I need to build a json object out of attr 'data-id'. Can a JSON object be a single 'array' of numbers?
I have got the code for this but I am struggling to build the JSON object, as follows:
code:
var displayed = {};
$('table#livefeed tr').each(function (i) {
var peopleID = $(this).attr("data-id");
//console.log("id: " + peopleID);
if(peopleID!="undefined") displayed += peopleID;
});
console.log(displayed);
However this does not work properly, I just end up with string of objects added together.

A JSON object can be an array of numbers.
Try something like this:
var displayed = [];
$('table#livefeed tr').each(function (i) {
var peopleID = $(this).attr("data-id");
if(peopleID!="undefined")
displayed.push(peopleID);
});
console.log(displayed);
To turn it into JSON,
JSON.stringify(displayed);

First you build and object then you use JSON.stringify(object); to create the string. But you also have an error. If you are checking peopleID to be defined you need to use typeof as an undefined attribute won't be the string 'undefined':
var displayed = [];
$('table#livefeed tr').each(function (i) {
var peopleID = $(this).attr("data-id");
//console.log("id: " + peopleID);
if(typeof(peopleID)!="undefined") displayed.push(peopleID);
});
console.log(displayed);
var jsonDisplay = JSON.stringify(displayed);
console.log("JSON: " + jsonDisplay);

Related

Pass dynamic json object value from dropdown

I am storing field value (Sales, ProductName) from json in an array named 'data[]' and 'name[]'.
Below is the code which works fine.
function onCompletedCallback(response, eventArgs) {
var chartlist = eval("(" + response.get_responseData() + ")");
var markup = " ";
//Display the raw JSON response
markup += response.get_responseData();
// alert(markup);
var jsonData=jQuery.parseJSON(markup);
// alert(jsonData);
//declaring arrays
var name = [];
var data = [];
$.each(jsonData.d.results, function (index, value) {
data.push(value.Sales);
name.push(value.ProductName);
});
}
Now what I want to pass field values from dropdown(ddlxField) in my UI, which holds all the fieldname of the list and pass it to json object while pushing data in 'name' array.
For now am choosing 'ProductName' form dropdown, i.e, xName=ProductName
var xName = document.getElementById("ddlxField").value;
$.each(jsonData.d.results, function (index, value) {
data.push(value.Sales);
name.push(value.xName); // xname value= ProductName
});
But after execution, xName is coming out to be undefined.
can anyone suggest what else can be done or where am going wrong?
Use value[xName] instead of value.xName.
The [] syntax need a string for key, just like xName.

How to parse read json elements with jquery

I have to create cart system in my mobile application, i want to store the id and the quantity of products, the id should be the key of my array (for modifying product quantity) , tried to use object instead of array but i get error: undefined is not a function when i try to read my json variable
by JSON.stringify(cart)
My cart code is like this
var cart = [];
var produit = {};
produit['qte'] = $('.'+id_prd).text();
produit['id_produit'] = id_prd;
cart[id_prd] = produit;
window.sessionStorage["cart1"]= JSON.stringify(cart);
return me
{"7":{"qte":"1","id_produit":7},"8":{"qte":"1","id_produit":8}}
when I tried to parse the json string with
var parsed = $.parseJSON(window.sessionStorage["cart1"]);
i get the error 'undefined is not a function'
when triying to read the json with
var i=0;
for (k in parsed) {
var k_data = parsed[k];
k_data.forEach(function(entry) {
alert(entry);
ch+=entry.id_produit;
if(i<parsed.length-1)
ch+= ',';
if(i==parsed.length-1)
ch+=')';
i++;
});
}
Can you clarify me the error cause, and if there's a solution to better read the json
The problem is that you are using k_data.forEach(function(entry) but forEach is for Arrays, and k_data is just a simple javascript object.
Try changing:
k_data.forEach(function(entry){
to this:
$(k_data).each(function(entry){
Even more, if the JSON is always in the same structure you posted, I think the each function is not necessary, maybe this is the way you are looking for:
var i=0;
var ch = "(";
for (k in parsed) {
var k_data = parsed[k];
alert(k_data);
ch+=k_data.id_produit;
ch+= ',';
i++;
}
ch = ch.substring(0, ch.length - 1) + ")";
You shouldn't need jQuery for this. The same JSON object you used to stringify has a parse function:
var parsed = JSON.parse(window.sessionStorage["cart1"]);
If that still breaks, there's probably something wrong with another undefined object.
You can try something like this:
<script type="text/javascript">
var finalArr = new Array();
var dataArr = new Array();
dataArr = window.sessionStorage["cart1"];
if (JSON.parse(dataArr).length > 0) {
for (var i = 0; i < JSON.parse(dataArr).length; i++) {
finalArr.push((JSON.parse(dataArr))[i]);
}
}
</script>

Adding an array to a Javascript object

I have some code I want to put into a JSON object ultimately. But first I want to create a javascript object and within that object add an array of values. Sounds simple enough but my approach seems wrong. First I create a basic object, the set a few fields. Lastly, iterate over a bunch of checkboxes and then, if one is checked at that value to an array.
At the last step I need to add that array to my object (myData) and then JSONify it.
Any ideas how I can do this, seems myData.push(filters); doesn't work...
Note that the object itself is not an array, I want to place an array IN the object.
var myData = new Object();
myData.deviceId = equipId;
myData.dateTo = dateTo
myData.dateFrom = dateFrom;
myData.numResults = $("#numResults").val();
var i=0;
var filters = [];
$('input[type=checkbox]').each(function () {
if (this.checked) {
allData += $(this).val() + ",";
filters[i] = {
filterIds: $(this).val()
};
++i;
}
});
myData.push(filters);
That's not how to add items to an Object, change
myData.push(filters);
to
myData.filters = filters;
Also, maybe change = new Object to = {}. There's no difference, but it's easier to read, because literal notation takes up less space.
Read more about Array.prototype.push
Use push to add elements to the filters array. Use property assignment to add another property to the myData object.
var myData = {
deviceId: equipId,
dateTo: dateTo,
dateFrom: dateFrom,
numResults: $("#numResults").val()
};
var filters = [];
$('input[type=checkbox]').each(function () {
if (this.checked) {
allData += $(this).val() + ",";
filters.push({
filterIds: $(this).val()
});
}
});
myData.filters = filters;
BTW, don't use new Object() to create an object, use {}.
Remove the need for an extra array and i.
var myData = {}
myData.deviceId = equipId;
myData.dateTo = dateTo
myData.dateFrom = dateFrom;
myData.numResults = $("#numResults").val();
myData.filters = [];
$('input[type=checkbox]').each(function () {
if (this.checked) {
allData += $(this).val() + ",";
myData.filters.push({
filterIds: $(this).val()
});
}
});

Getting undefined in dropdown from json content

EDIT 2
Check the fiddle - http://jsfiddle.net/SN5zT/2/
Following is the fiddle for which I am not sure why I am getting undefined in dropdown.
My fiddle - http://jsfiddle.net/z6GDj/
var res = '{"allSportPosition":{"25":"Forwards (Strickers)","27":"Fullbacks (Defenders)","28":"Goalkeeper ","26":"Midfielders"}}';
try {
var sportPositionOptions = '';
var parsedJson = JSON.parse(res);
var allSportPosition = parsedJson.allSportPosition;
var values = new Array();
$.each(allSportPosition, function (index, value) {
values[index] = value;
});
//alert(values.length);
values.sort();
$.each(values, function (atIndex, atValue) {
sportPositionOptions = sportPositionOptions + '<option value="' + atIndex + '">' + atValue + '</option>';
});
$(sportPositionOptions).appendTo("#player");
} catch (e) {
alert("Parsing error:" + e);
}
$.each is automatically sorting keys to 25,26,27,28 for res.
Please explain the reason of this and why I am getting undefined ?
Let me know If i need to explain it more, I will surely do it :)
EDIT
Please explain the reason why it is getting sorted automatically http://jsfiddle.net/SN5zT/
Try
values.push(value);
instead of
values[index] = value;
Fiddle Link
The following script is working, I also figured out where the "undefineds" came from.
http://jsfiddle.net/z6GDj/3/
var res = '{"allSportPosition":{"25":"Forwards (Strickers)","27":"Fullbacks (Defenders)","28":"Goalkeeper ","26":"Midfielders"}}';
try{
var sportPositionOptions = '';
var parsedJson = JSON.parse(res);
var allSportPosition = parsedJson.allSportPosition;
var values = allSportPosition;
//$.each(allSportPosition, function(index, value) {
// values[index] = value;
//});
//alert(values.length);
$.each(values,function(atIndex, atValue){
sportPositionOptions = sportPositionOptions+'<option value="'+atIndex+'">'+atValue+'</option>';
});
$(sportPositionOptions).appendTo("#player");
}
catch(e){
alert("Parsing error:"+ e);
}
The array is sorted automatically, because the keys are set correctly.
see http://www.w3schools.com/js/js_obj_array.asp. "An array can hold
many values under a single name, and you can access the values by
referring to an index number."
Or: Change the index, and you´re changing the order. (index indicates the order).
The undefined values are created by javascript default, check the last answer in here (How to append something to an array?)
"Also note that you don't have to add in order and you can actually
skip values, as in
myArray[myArray.length + 1000] = someValue;
In which case the values in between will have a value of undefined."
Since you are passing an object to each(), jquery passes the key as the index parameter. In your object, the keys are ranged from 25 to 28. Setting the array using the values[25] on an empty array will expand the array to index 25, with the first 25 elements undefined. Using values.push(value) will append the value at the end of the array.
$.each is doing the following assignment that is why you are getting so many undefined
values[25] = "Forwards (Strickers)"
values[26] = "Midfielders"
values[27] = "Fullbacks (Defenders)"
values[28] = "Goalkeeper"
During $.each browsers will automatically sort the keys if the keys are integer, one way to avoid this is use non integer keys
What you need to do is define your options before you sort them , and then append them to your select:
var res = '{"allSportPosition":{"25":"Forwards (Strickers)","27":"Fullbacks (Defenders)","28":"Goalkeeper ","26":"Midfielders"}}';
try {
var sportPositionOptions = '',
parsedJson = JSON.parse(res),
allSportPosition = parsedJson.allSportPosition,
options = new Array();
$.each(allSportPosition, function (index, value) {
options[index] = $('<option></option>', {
value: index,
text: value
});
});
$.each(options, function (index) {
$('#player').append(options[index]);
});
} catch (e) {
alert("Parsing error:" + e);
}
jsfiddle: http://jsfiddle.net/z6GDj/11/

JS Object values start with 'undefined'

I am trying to use an array as a key value type scenario and it is working with the exception that every value starts with 'undefined'. I believe this is due to the initial assignment being a += operator however I am not sure how to resolve it.
This is the code stripped of a lot of string concats....
var phasehtml = {};
$.each(json, function (i, item) {
phasehtml[item.Phase] += 'item:'+item.ID;
});
Basically I am trying to append the string to the appropriate key....
You can change the code to only append the ID if there's already IDs:
var phasehtml = {};
$.each(json, function (i, item) {
// Use the existing value for the phase, or an empty string that we can append to
var existingValue = (phasehtml.hasOwnProperty(item.Phase) ? phasehtml[item.Phase] : "");
phasehtml[item.Phase] = existingValue + 'item:' + item.ID;
});
That's assuming that you want phasehtml to contain an appended lists of the form "item:1item:2" for each phase.
The array you have posted is empty.
var phasehtml = {};
It seems that is the cause the following statement
phasehtml[item.Phase]
is being evaluated to "undefined".
Hmmm,
got the problem.
In your code you are trying to add with that value which is previously not defined that's why this error is occur.
In your code you have not initialize the variable that you are adding.
So try this:
var phasehtml = {};
$.each(json, function (i, item) {
phasehtml[item.Phase] = "";
phasehtml[item.Phase] += 'item:'+item.ID;
});
In this first assign some value, here is blank and then use that index of array.

Categories