I have a JSON String in a JavaScript var, how I can loop through JSON string to make script like this output?
INSERT INTO table VALUES ('$var1', '$var2', '$var3', '$varN');
Is there is any direct way to fill a table from a json string?
JSON Example:
{"table":[{"id":"1","name":"David","nick":"falk","year":"20"},{"id":"2","name":"Mark","nick":"master","year":"50"},{"id":"3","name":"jhon","nick":"jx","year":"20"},{"id":"4","name":"Maria","nick":"beauty","year":"20"}]}
We assign a variable name to the json object
var table = {"table":[{"id":"1","name":"David","nick":"falk","year":"20"},{"id":"2","name":"Mark","nick":"master","year":"50"},{"id":"3","name":"jhon","nick":"jx","year":"20"},{"id":"4","name":"Maria","nick":"beauty","year":"20"}]};
Using jquery
loop over the variable table which have the property table.
$.each(table.table,function(index, item){
//INSERT INTO table VALUES ('$var1', '$var2', '$var3', '$varN');
console.log("INSERT INTO table VALUES('"+ item.id + "','"+ item.name + "','"+ item.nick + "','"+ item.year +"')");
});
take a look in jsfiddle http://jsfiddle.net/628Cb/
You can use the for loop to iterate over the array contained by the table object.
var p = {"table":[{"id":"1","name":"David","nick":"falk","year":"20"},{"id":"2","name":"Mark","nick":"master","year":"50"},{"id":"3","name":"jhon","nick":"jx","year":"20"},{"id":"4","name":"Maria","nick":"beauty","year":"20"}]};
var arr = p["table"];
for(var i=0;i<arr.length;i++){
var obj = arr[i];
alert(obj["id"] + " "+ obj["name"] + " "+ obj["nick"]+ " "+obj["year"]);
INSERT INTO table VALUES (obj["id"], obj["name"], obj["nick"], obj["year"]);
}
Related
Hi I have an Array which I would like to remove an element from.
After the deletion of the element from the array, it is saved to localStorage.
However, after loaded from storage it shows that the first element is missing ].
This is the code which I am using to perform the deletion:
var dataSet = (localStorage.getItem('expenditureListFromStorage'));
console.log(dataSet);
//var dataSet = "[" + dataSet + "]";
var dataSet = "[" + dataSet + "]";
console.log("Before parsing" + dataSet);
console.log(dataSet);
var dataSet = JSON.parse(dataSet);
//dataSet.push(dataSet.splice(dataSet.indexOf(selectedExpenditure), 1)[0]);
dataSet.unshift(dataSet.splice(dataSet.indexOf(selectedExpenditure), 1)[0]);
//dataSet.unshift(selectedExpenditure);
console.log("Before Deletion" + dataSet);
dataSet.shift();
//dataSet.pop(dataSet.indexOf(selectedExpenditure), 1);
//dataSet.splice(dataSet.indexOf(selectedExpenditure), 1);
console.log("After Deletion" + dataSet);
localStorage.setItem('expenditureListFromStorage', dataSet);
This is the code which I am using when saving the first element to the array:
if (localStorage.getItem('expenditureListFromStorage') === null)
{
var newExpenditure = [];
newExpenditure.push([tempExpenditureName, tempExpenditureCategory, tempExpenditureDescription, tempExpenditureOccurrence, tempExpenditurePrice, tempExpenditureDate]);
newExpenditure = "[" + newExpenditure + "]";
localStorage.setItem('expenditureListFromStorage', newExpenditure);
console.log(localStorage.getItem('expenditureListFromStorage'));
}
This is the code I am using to add subsequent elements (this piece of code is placed just after the code which saves the first element of an array):
else
{
var newExpenditure = [];
newExpenditure.push([tempExpenditureName, tempExpenditureCategory, tempExpenditureDescription, tempExpenditureOccurrence, tempExpenditurePrice, tempExpenditureDate]);
newExpenditure = "[" + newExpenditure + "]";
console.log("New Expenditure from Form = " + newExpenditure);
var expenditureArrayList = (localStorage.getItem('expenditureListFromStorage'));
console.log("expenditureArrayList from Storage before parsing" + expenditureArrayList);
expenditureArrayList = expenditureArrayList + "," + newExpenditure;
console.log("expenditureArrayList from Storage after parsing" + expenditureArrayList);
localStorage.setItem('expenditureListFromStorage', (expenditureArrayList));
console.log(expenditureArrayList);
}
If I do not save these elements this way, I cannot retrieve the array again after loading from localStorage.
I am trying to work with an array in this format
[["Array1Value1", "Array1Value2", "Array1Value3"],["Array2Value1","Array2Value2","Array2Value3"]]
This array would then be retrieved from localStorage and displayed as an HTML table using the dataTables plugin. However the problem is that when I am deleting an element and saving the array without this array, something is breaking the array and its first element.
Could someone help me out please?
I have an ajax call that returns a Serialized JSON string with various keys and values within it, I want to loop through these values and assign each individual key and value to a different label, I already have 8 labels set up. (I am quite new to Javascript so any help or constructive feedback would be greatly appreciated)
Haven't tried much as I am quite new to JavaScript
var obj = response.ret.SearchCriteria;
var resultJSON = obj;
var result = $.parseJSON(resultJSON);
var count = Object.keys(result).length;
for (i = 1; i < count; i++) {
var c = $('#lbl' + [i]);
$.each(result, function(k, v) {
c.text(k + ' is ' + v);
});
};
I have 6 labels and the last item of the JSON array (String) is displayed in each label
I believe your issue is why only last item of JSON array is being displayed in each label.
This is because of c.text(k + ' is ' + v).
Here the existing text content is replaced with every iteration of 'each' loop
Instead, you can consider doing this, which will append existing content as well with $.each loop.
c.text(c.text() + k + ' is ' + v)
OR
Simply
c.append( k + ' is ' + v)
If I am wrong in my assumption, please describe your scenario more, so that we can help you out :)
My json returns below shown set of array of objects and I need to access the data inside it. In the console this is what the response looks like
What i am trying to do is to access the object to get the subcategoryid and subcategoryname then display it inside a dropdown list. Here is my code for it
$.get('ajax-subcat?cat_id=' + cat_id, function(data)
{
console.log(data);
$('#subcategory').empty();
$.each(data, function(index, subcatObj)
{
alert(subcatObj);
$('#subcategory').append('<option value="' + subcatObj.Object.subcategoryid +'">' + subcatObj.subcategoryname +'</option>');
});
});
The thing I don't know is how to access the data inside the object. Any ideas?
Try this:
JAVASCRIPT
for (var i = 0; i < data.length; i++) {
console.log(data[i].subcategoryid);
}
Assuming that you have a select element in markup:
<select id="mySelectElement"></select>
Try this to iterate the object and fill the combo box:
$.get('ajax-subcat?cat_id=' + cat_id, function(data) {
// Get a reference to the target element
var selectTarget = $('#mySelectElement');
// Iterate over the response data
for (var i in data) {
// For every object in array, append a new option element
selectTarget.append($('<option value="' + data[i].subcategoryid + '">' + data[i].subcategoryname + '</option>'));
}
});
For this purpose, you can use underscore.js library to get whole data corresponding to particular key in the form of array.
_.pluck(data, 'subCategoryid') // array of all values corresponding to 'subcategoryid'
I'm using the following code/data to display a list of our top-earning students in each House.
The data
Attachment 1: User_Info is an array of Objects
Attachment 2: User_Info is an array of Objects such as this
Attachment 3: Database_Info is an Object like this
The code
HPAnalysisObject.dispHPTotals = function(User_Info, Database_Info) {
// See attachments 1 and 2
console.log(User_Info);
// See attachment 3
console.log(Database_Info);
// "label" is just a text title, like "Eagles"
var html = '<h2>' + HPAnalysisObject.label + '</h2>' +
// "TotalPoints" is an integer figure
'<div id="total">' + Database_Info.TotalPoints + '</div>';
// create the table to display
html += '<table><tr><th class="name">Name</th><th class="points">Points</th></tr>';
// use "for, in" to access the value of the object key (which is the user's ID)
for (var id in Database_Info.UserDetails) {
html += '<tr>';
for (var i = 0; i < User_Info.length; i++) {
if (User_Info[i].id == id) {
// if the User_Info and Database_Info objects match up on the User's ID, add table cells to our html variable
html += '<td class="name">' + User_Info[i].firstname + ' ' + User_Info[i].surname + '</td><td class="points">' + Database_Info.UserDetails[id] + '</td>';
}
}
html += '</tr>';
}
html += '</table>';
$('div#display').html(html);
};
The problem
Oddly, in Firefox, these students display in the correct numerical order, as the students are received from my PHP script.
However, in Google Chrome and Internet Explorer, they appear in a seemingly-random order!
My first thought was to order the object, but having read a few questions on here, it seems like ordering objects isn't the best practice.
Can I rewrite this code so that I display the same tabular data - just in the right order on every browser?
Thanks in advance,
In most languages, you cannot assume that object attributes occur in any particular order.
One solution might be to add an accessor to each entry in UserDetails such as:
UserDetails={
ID:{
accessor:1,
id: ID
}
}
And then sort the records on UserDetails[ID].accessor.
Another might be to construct UserDetails as an array of elements which encode key values as "key:value", splitting each retrieved elements on /:/ as in:
[
"90030:87"
...
]
EDIT
Assuming
var userDetails={
a:{i:3,key:'third'},
b:{i:1,key:'first'},
c:{i:2,key:'second'}
};
where i is the accessor, you can create a sorted array of objects using
var sortedObjs=Object.keys(userDetails)
.map(function(k){ return userDetails[k] })
.sort(function(left,right){ return left['i']-right['i'] });
which extracts keys from userDetails, creates an array of the keyed elements via map and sorts the resulting elements by their accessor value such that
console.log(sortedObjs.map(function(elt){return elt.key}).join(','))
will print to the console:
first,second,third
Objects are an unsorted mapping of keys to values, their order is never guaranteed.
When I get anything like this, I like to build an array using the ID as numeric keys. For instance, something like this in PHP:
$out = Array();
while($row = database_get_row($set)) { // replace with your choice of database library
$out[$row['id']] = $row;
}
ksort($out);
$out = array_values($out);
In this way, you can ensure that the array is in order of increasing ID, and then pass that array to JavaScript for use in a for(i=0;i<l;i++) loop.
You'll have to sort Database_Info.UserDetails using an array wrapper:
// test data using same data as example but with no order
var Database_Info = {
UserDetails : {
137473 : 87,
90132 : 126,
90057 : 79,
90030 : 87,
90095 : 82
}
}
var objWrapper = [];
for (key in Database_Info.UserDetails) {
objWrapper.push(key);
}
objWrapper.sort(); // default sort = numeric order ascending
for (a = 0, b = objWrapper.length; a < b; a++) {
var userInfo = Database_Info.UserDetails[objWrapper[a]];
// do something interesting
console.log(userInfo);
}
I decided to wrap my Objects in a sortable array. This appeared to do the trick.
HPAnalysisObject.dispHPTotals = function(User_Info, Database_Info) {
// make a sortable array
var Combined_Info = [];
// "label" is just a text title, like "Eagles"
var html = '<h2>' + HPAnalysisObject.label + '</h2>' +
// "TotalPoints" is an integer figure
'<div id="total">' + Database_Info.TotalPoints + '</div>';
// create the table to display
html += '<table><tr><th class="name">Name</th><th class="points">Points</th></tr>';
// use "for, in" to access the value of the object key (which is the user's ID)
for (var id in Database_Info.UserDetails) {
for (var i = 0; i < User_Info.length; i++) {
if (User_Info[i].id == id) {
var StudentInfo = { name: User_Info[i].firstname + ' ' + User_Info[i].surname, points: Database_Info.UserDetails[id] };
Combined_Info.push(StudentInfo);
}
}
}
Combined_Info.sort( function(a, b) {
return b.points - a.points;
});
for (var i = 0; i < Combined_Info.length; i++) {
html += '<tr>';
html += '<td class="name">' + Combined_Info[i].name + '</td><td class="points">' + Combined_Info[i].points + '</td>';
html += '</tr>';
}
html += '</table>';
$('div#display').html(html);
};
I'm looking to loop through a JSON array and display the key and value.
It should be a simplified version of the following post, but I don't seem to have the syntax correct: jQuery 'each' loop with JSON array
I also saw the post Get name of key in key/value pair in JSON using jQuery?, but it also seemed like lots of code for a simple activity.
This illustrates what I'm looking for (but it doesn't work):
var result = '{"FirstName":"John","LastName":"Doe","Email":"johndoe#johndoe.com","Phone":"123 dead drive"}';
$.each(result, function(k, v) {
//display the key and value pair
alert(k + ' is ' + v);
});
There is no mandatory jQuery requirement, but it is available. I can also restructure the JSON if it cuts down the required code.
You have a string representing a JSON serialized JavaScript object. You need to deserialize it back to a JavaScript object before being able to loop through its properties. Otherwise you will be looping through each individual character of this string.
var resultJSON = '{"FirstName":"John","LastName":"Doe","Email":"johndoe#johndoe.com","Phone":"123 dead drive"}';
var result = $.parseJSON(resultJSON);
$.each(result, function(k, v) {
//display the key and value pair
alert(k + ' is ' + v);
});
Live demo.
var obj = $.parseJSON(result);
for (var prop in obj) {
alert(prop + " is " + obj[prop]);
}
You can get the values directly in case of one array like this:
var resultJSON = '{"FirstName":"John","LastName":"Doe","Email":"johndoe#johndoe.com","Phone":"123 dead drive"}';
var result = $.parseJSON(resultJSON);
result['FirstName']; // return 'John'
result['LastName']; // return ''Doe'
result['Email']; // return 'johndoe#johndoe.com'
result['Phone']; // return '123'
The following should work for a JSON returned string. It will also work for an associative array of data.
for (var key in data)
alert(key + ' is ' + data[key]);
Parse the JSON string and you can loop through the keys.
var resultJSON = '{"FirstName":"John","LastName":"Doe","Email":"johndoe#johndoe.com","Phone":"123 dead drive"}';
var data = JSON.parse(resultJSON);
for (var key in data)
{
//console.log(key + ' : ' + data[key]);
alert(key + ' --> ' + data[key]);
}
The best and perfect solution for this issue:
I tried the jQuery with the Ajax success responses, but it doesn't work so I invented my own and finally it works!
Click here to see the full solution
var rs = '{"test" : "Got it perfect!","message" : "Got it!"}';
eval("var toObject = "+ rs + ";");
alert(toObject.message);