appendgrid - Getting grid data as a JSON Object instead of regular serialization - javascript

In the example listed here, how can I get the grid data as JSON?
Reference Link
The JQuery Serialize works, but it would be nice if I am able to get each row as a JSON Object, so I can parse the data.?

You can use the .appendGrid('getAllValue') function to get the grid data as javascript objects. You can parse them directly or encode them as JSON.
Example:
var data = $('#tblAppendGrid').appendGrid('getAllValue')
returns an array where each element is the data from one table row as object.
data[0] will be the first row.
JSON.stringify(data) will be a JSON string with all the data from your table

You can create element on run time, as per the JSON object length, you have to use for each or simple for loop and iterate the json data upto length.
Like :
for(var i=0; i<=json_object.length; i++) {
console.log(json_object.user[i].name); var ele_block =
document.createElement('div'); $(ele_block).addClass("block"+i);
ele_block.appendChild(block_name);
$("#name_block").append(ele_block);
}
Create an element where the newly generated data will be added.
<div id="name_block"></div>

You can just use JQuery Serialize to get the seriesed string and then use the helper function uri_decoder to decode it to an Object.
var decode, seriesed, uri_decoder;
seriesed = "a=1&b=2&c=3&d=4&e=5";
uri_decoder = function(component_unpacker) {
if (component_unpacker == null) {
component_unpacker = (function(s) {
return s;
});
}
return function(str) {
var d, i, j, k, len, ref, ref1, ref2, s, v;
d = {};
ref1 = (ref = str.match(/[^?=&]+=[^&]*/g)) != null ? ref : [];
for (i = 0, len = ref1.length; i < len; i++) {
s = ref1[i];
ref2 = s.match(/([^=]+)=(.*)/), j = ref2.length - 2, k = ref2[j++], v = ref2[j++];
d[decodeURIComponent(k)] = component_unpacker(decodeURIComponent(v));
}
return d;
};
};
decode = uri_decoder();
console.log(json(decode(seriesed)));
try these code here
this util is provided by this project.

Related

How to map DOM tags to dictionary?

I need to find a way to map all the tags that appear in a DOM to key:value dictionary (With structure of TagName:Attributes).
I have to do that with Javascript or JQuery code.
Any ideas?
Thanks!
According to this Javascript: How to loop through ALL DOM elements on a page? you can list all elements of the document using getElementsByTagName():
var all = document.getElementsByTagName("*");
for (var i=0, max=all.length; i < max; i++) {
// Do something with the element here
}
and looking at this Creating a .net like dictionary object in Javascript a dictionary can be built like:
var dictionary = {};//create new object
dictionary["key1"] = value1;//set key1
var key1 = dictionary["key1"];//get key1
or further, if you want to add specific methods:
function Dictionary(){
var dictionary = {};
this.setData = function(key, val) { dictionary[key] = val; }
this.getData = function(key) { return dictionary[key]; }
}
var dictionary = new Dictionary();
dictionary.setData("key1", "value1");
var key1 = dictionary.getData("key1");

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>

Map values from external json lookup into array as new key/value pairs

I am trying to map new values (from an external json file) into an array (array of arrays or KV pairs, generated from a php file query to mysql) in javascript/jQuery.
The structure of the array is:
"results":
[{"gender":"Male","DOB":"1993-09-22","location":"Main","procCode":"43653","preopDx1":"783.3","procedDate":"2008-06-02"},{"gender":"Female","DOB":"2001-11-07","location":"South","procCode":"11403","preopDx1":"216.5","procedDate":"2010-01-01"},...]
The json file looks like this:
[
{
"CPT": "10021",
"RVU": "1.27"
},
{
"CPT": "10022",
"RVU": "1.27"
}
]
The idea is to
a) Loop thru the myarray values and find each procCode
b) Match this procCode with the identical cpt code in the json file, and
c) Attach each new key/value pair to each 'row' of myarray
function addRVU (myarray, myjson){
var newObj = $.map(myarray, function (i,res){
if(myarray[i].procCode == myjson[i].CPT){
return myarray[i].RVU = myjson[i].RVU;
}
}
}
Thanks in advance!
// First, convert JSON file into an object keyed off CPT code:
var jsonObj = {};
for (var i = 0; i < json.length; i++) {
jsonObj[json[i].CPT] = json[i];
}
// Now update myarray elements
for (i = 0; i < myarray.length; i++) {
// $.extend copies properties from 2nd object into 1st object
$.extend(myarray[i], jsonObj[myarray[i].procCode]);
}
for if(myarray[i].procCode == myjson[i].CPT), you only matched the json and array with same index. loop to match all element in json should fix your problem.
or something like using a hash to map the RVU
h = {};
$.each(json, function(i, e){
h[e.CPT] = e.RVU;
});
$.each(ar, function(i, e){
e.RVU = h[e.procCode];
});

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

Need help traversing JSON object in Javascript

I have code that calls a WCF service and returns a JSON string to the client. Below is the javascript function I am trying to use to parse the JSON but can not figure out how to traverse it.
Here is the function
loadDropDown: function(result, ddl, defaultItem) {
var _data = result.get_object();
//Sys.Serialization.JavaScriptSerializer.deserialize(result, true);
this.clearDropDown(ddl);
this.createOption(ddl, defaultItem, '');
for (var i = 0; i < _data.length; i++) {
var _item = _data[i];
var _option = this.createOption(ddl, _item.Text, _item.Value);
}
ddl.disabled = false;
}
Here is the JSON
{
"d": "[{\"Attributes\":{\"Keys\":[],\"Count\":0,\"CssStyle\":{\"Keys\":[],\"Count\":0,\"Value\":null}},\"Enabled\":true,\"Selected\":false,\"Text\":\"Lexus\",\"Value\":\"Lexus\"},{\"Attributes\":{\"Keys\":[],\"Count\":0,\"CssStyle\":{\"Keys\":[],\"Count\":0,\"Value\":null}},\"Enabled\":true,\"Selected\":false,\"Text\":\"Acura\",\"Value\":\"Acura\"}]"
}
any suggestions on why this is not working? Note: I am not using jquery in the solution.
You shouldn't be generating that json. Instead, you should be outputting
{
"d": [{"Attributes":{"Keys":[],"Count":0,"CssStyle":{"Keys":[],"Count":0,"Value":null}},"Enabled":true,"Selected":false,"Text":"Lexus","Value":"Lexus"},{"Attributes":{"Keys":[],"Count":0,"CssStyle":{"Keys":[],"Count":0,"Value":null}},"Enabled":true,"Selected":false,"Text":"Acura","Value":"Acura"}]
}
(quotes removed from "d" value)
There's no reason to convert json to a string before putting it in a json object! Just put the json straight in.
You should be able to just eval() the object (or use JSON parsing from Crockford) and access your properties in regular object notation. You may need to unescape your identifiers first, though.
You need to do eval(_data) before you use it as a javascript array.
for ex:
var _rawdata = result.get_object();
var _data = eval(_rawdata);
//Sys.Serialization.JavaScriptSerializer.deserialize(result, true);
this.clearDropDown(ddl);
this.createOption(ddl, defaultItem, '');
for (var i = 0; i < _data.length; i++) {
var _item = _data[i];
var _option = this.createOption(ddl, _item.Text, _item.Value);
}
ddl.disabled = false;

Categories