I have a JSON as follows
{
columns : [RULE_ID,COUNTRY_CODE],
RULE_ID : [1,2,3,7,9,101,102,103,104,105,106,4,5,100,30],
COUNTRY_CODE : [US,US,CA,US,FR,GB,GB,UM,AF,AF,AL,CA,US,US,US]
}
I need to retrive the column names from the columns entry and then use it to search the rest of the entries using jquery.
For example I get each column using
jQuery.each(data.columns, function(i,column))
I need to loop throgh the rest of the entries using the values I get from the previous loop. ie without hardcoding COUNTRY_CODE or RULE_ID.
What is the best way to do that using Jquery?
jQuery.each(data.columns, function(i,column) {
jQuery.each(data[column], function(i, row) {
....
});
});
Some comments:
Paolo is right, you can use data[column] to get the list of values:
jQuery.each(data.columns, function(iCol,column) {
jQuery.each(data[column], function(iRow, row) {
....
});
});
Do you need the columns information ? You could get the list of "columns" by iterating directly over data:
for( var column in data )
{
jQuery.each(data[column], function(i, row) {
....
});
}
Not really a question but your JSON is not valid JSON, I hope this was only an example and not your real data:
{
"columns" : ["RULE_ID","COUNTRY_CODE"],
"RULE_ID" : [1,2,3,7,9,101,102,103,104,105,106,4,5,100,30],
"COUNTRY_CODE" : ["US","US","CA","US","FR","GB","GB","UM","AF","AF","AL","CA","US","US","US"]
}
Related
I want to fetch only 1st element of json array
my json data :
{
id:"1",
price:"130000.0",
user:55,
}
{
id:"2",
price:"140000.0",
user:55,
}
i want to access the price of 1st json element
price : "13000.0"
my code
$.each(data_obj, function(index, element) {
$('#price').append(element.price[0]);
});
but my output
is '1'
Assuming that you have array of objects
var arr = [{
id:"1",
price:"130000.0",
user:55,
},
{
id:"2",
price:"140000.0",
user:55,
}]
console.log(arr[0].price)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
You data isn't valid JSON, JSON data key must be wrap within double quote, but your data isn't wrapped in double quote
var data = [{
"id":"1",
"price":"130000.0",
"user":55
},{
"id":"2",
"price":"140000.0",
"user":55
}]
console.log(data[0]["price"]);
Hello You just need to add [] from starting and ending point of your json string. see here var data = JSON.parse( '[{ "id":"1","price":"130000.0","user":55},{"id":"2","price":"140000.0","user":55}]');
var priceValue = 0;
$.each(data, function(index, element) {if(index == 0){ priceValue = element.price;}});console.log(priceValue);
Your answer will be 13000.0
The element having the your JSON data means, we can able to use below code to get the first JSON data.
element[0].price
Thanks,
You are using for each loop and in function you get 2 params first one is index and second is the element itself. So this will iterate through all elements.
$.each(data_obj, function(index, element) {
$('#price').append(element.price);
});
If you just want to get first element
$('#price').append(data_obj[0].price);
var my_first_json_obj = data_obj[0]; // Your first JSON obj (if it's an array of json object)
var my_price = my_first_json_obj.price; // Your price
$('#price').append(my_price);
If you want only the first item's price, you don't need a loop here.
$('#price').append(data_obj[0].price);
would work here.
For further reading you can refer here
Following is the solution worked for my problem
I use return false;
$.each(data_obj, function(index, element) {
$('#price').append(element.price[0]);
return false;
});
Which gives only 1st value of array elements.
I have table that first time is server - side rendered. I want on some click event refresh data in table.
Problem is how to "bind" specific json object propertie to specific column. I receive json object with array of objects where only some of properties are interesting me.
I want
Table column -- json object propertie
ID -- id
Name -- name + surname
Cooperation -- scCooperationCollection
Skills -- scSkillsCollection
Experience -- workExperience
HTML table: http://pastebin.com/b5yRWsGe
JS reload table: http://pastebin.com/GzS8tpV6
JSON example : http://pastebin.com/AyBSrSui
See columns.data or columns.render options on how to bind source data to table columns or produce custom content for a cell.
You can access source data properties using dotted notation in columns.data or even join arrays with [] notation. For more complex data rendering like joining two fields, use columns.render instead.
For example:
var table = $('#example').DataTable({
ajax: {
url: 'https://api.myjson.com/bins/3x4ql',
dataSrc: 'aaData'
},
columns: [
{ data: "id" },
{
data: null,
render: function(data, type, full, meta){
return full['name'] + ' ' + full['surname'];
}
},
{ data: "scCooperationCollection[,].scFields.name" },
{ data: "scSkillsCollection[,].scFields.name" },
{ data: "workExperience" }
]
});
See this jsFiddle for code and demonstration.
You can navigate through the desired properties in returned json object and tie up same to your table something like below:
table.on( 'xhr', function () {
var json = table.ajax.json();
var obj = JSON.parse(json)
var tableJson = {"ID":obj.aaData[0].id};
console.log(json);
} );
I am new to JSON and jquery. I have the following use-case for which I need some help.
I need to create an array of objects in the following format:
{ "endpoint" : [
{ "ip": "16.140.23.90", "mac": "a2:35:67:e7" },
{ "ip": "16.140.23.91", "mac": "36:b1:79:ab" }
]
}
This is a sample of what I need (representing two rows only, there can be more). Now the value of ip and mac I need to add by iterating over a table's selected rows.
E.g. there is a table on the GUI in which each row is having two columns "IP" and "MAC". I need to get the data of the selected rows in the above format.
How do I form the JSON array in the above format when I need to add the values of the attributes while iterating? Anything I can do using JSON.stringify API? If yes, then how do I form the string which I can pass to JSON.stringify which results in the above format?
Any help will be highly appreciated.
If this is your table (first cell is ip and 2nd cell is mac)
<table id='tbl'>
<tr><td>16.140.23.90</td><td>a2:35:67:e7</td></tr>
<tr><td>16.140.23.91</td><td>36:b1:79:ab</td></tr>
</table>
Pure JS
var ips = { "endpoint" : [] };
var tbl = document.getElementById('tbl');
for (var i=0; i<tbl.rows.length; i++) {
ips["endpoint"].push({
"ip" : tbl.rows[i].cells[0].innerHTML,
"mac" : tbl.rows[i].cells[1].innerHTML
});
}
Fiddle
jQuery
var ips = { "endpoint" : [] };
$(document).ready(function() {
$('#tbl tr').each(function(i) {
ips["endpoint"].push({
"ip" : $(this).find('td:eq(0)').text(),
"mac" : $(this).find('td:eq(1)').text()
});
});
var json = (JSON.stringify(ips));
document.getElementById('json').innerHTML = json;
});
Fiddle
The first answer is good. But since this question is in regard to jquery, I provide a similar solution using jquery to manipulate the DOM.
The table is still the same:
<table id='tbl'>
<tr><td>16.140.23.90</td><td>a2:35:67:e7</td></tr>
<tr><td>16.140.23.91</td><td>36:b1:79:ab</td></tr>
</table>
The javascript code to creat the json object:
var ips = { "endpoint": [] };
var rows = $('#tbl tr');
for (var i = 0; i < rows.length; i++) {
ips["endpoint"].push({
"ip": rows.eq(i).find("td").eq(0).text(),
"mac": rows.eq(i).find("td").eq(1).text()
});
}
Fiddle
JSON is just a serialized representation of javascript objects, so just make the objects in javascript and then serialize using the JSON.stringify method. If you're not sure how to make a javascript object and add values to an array, then you should do a little googling, since that's pretty basic stuff.
I want to make specific json from table. I have a table, which has rows and 4 columns.
Here is my table I want to build an jsonarray from the table.
First value in the left column is key of json and last value in the right column is a valueof json.
I mean I want to get from table jsonarray, it must look as
json_from_form = [{color: 'id',
name: "mouse",
x: "table",
y: "book"}];
I have tried to build json, but have a problem with structure and setting a key in json object.
Please help me to buld right structure of json object.
var json_from_form_tmp = {};
$('#table').find('tbody tr').each(function (i) {
//var name = $(this).find('td:first').text();
json_from_form_tmp[i] = {
imd: $(this).find('td:eq(3) input').val()
};
});
console.log(json_from_form_tmp);
Here is my DEMO
You should use the jQuery map-function for this, here is an example:
$(function () {
var m = $("table tr").map(function (index, e) {
return {
color: $(e).children().eq(0).text(),
name: $(e).children().eq(1).text()
}
}).get();
});
Where m will be an array of objects as defined inside the map function.
To set a property of the object (json_from_form_tmp), use the ['propertyName'] notation.
//get the name of the property from the first column
var name = $(this).find('td:first').text();
//use that name as the name of the property. Your value fetch was right!
json_from_form_tmp[name] = $(this).find('td:eq(3) input').val();
Here is your fiddle with a tiny modification.
http://jsfiddle.net/bMzq8/32/
What I want to do is set an icon for each category using jQuery. So far the code looks like this:
var category = $(".odd, .even").children('.views-field-field-category').text();
if (category=="funny") {
$(".odd, .even").children('.views-field-field-category').html('image-tag');
}
Since the variable category gathers all of the category values in that page and combines them (so that it looks like "funny gifs videos gifs" etc) I've decided that I need an array to hold them each seperately. Now I've tried to do it in various ways, but without any success. Can you please help and show me how to set it up so that I could use if (category[i]=="funny") { do this }?
You can create an object:
var o = {
'funny' : 'html-tag',
'gifs' : 'html-tag2',
'crazy' : '...'
}
And use html callback function.
$(".odd, .even").children('.views-field-field-category').html(function(i, html){
var prop = $(this).text().toLowerCase();
return o[prop];
})