json foreach array of arrays with jquery - javascript

[
[
{
"Id": 3,
"Code": "232",
"TicketImage": "0"
}
],
[
{
"Id": 1,
"Code": "23",
"TicketImage": "1"
},
{
"Id": 2,
"Code": "24",
"TicketImage": "1"
}
],
[]
]
I have this JSon object which I m trying to parse.
var res = jQuery.parseJSON(JSON.stringify(obj.Message));
$.each(res, function (i, tickets) {
$.each(tickets, function (i, ticket) {
console.log($(this));
});
});
When i try this i get zillions of popups with letters. but i want object.
How can i parse this JSON data?
UPDATE:
$.each(res, function (i, tickets) {
$.each(tickets, function (i, ticket) {
console.log(ticket.Code);
console.log(ticket.TicketImage);
});
});
This did it.

Careful you are overriding the i variable :
$.each(res, function (i, tickets) {
$.each(tickets, function (j, ticket) {
console.log(this);
// as a full string
console.log(this.ticketId+' : '+JSON.stringify(this));
});
});
​Besides this small thing, your loop is correct, you don't need the jquery wrapper on your 'this'. in $.each(array,function(k,v){}) , the k variable is the key to retrieve the current object and v it's value so you could also access it by doing this :
$.each(res, function (i, tickets) {
$.each(res[i], function (j, ticket) {
console.log(res[i][j].ticketId+' : '+res[i][j]);
// which is the exact same thing as :
console.log.(ticket);
// and even this:
console.(this);
});
});
The same code using 'this' :
$.each(res, function (i, tickets) {
$.each(this, function (j, ticket) {
console.log(this.ticketId+' : '+this);
});
});
using each value :
$.each(res, function (i, tickets) {
$.each(tickets, function (j, ticket) {
console.log(ticket.ticketId+' : '+ticket);
});
});

Try:
var res = jQuery.parseJSON(eval(obj.Message));

Related

Jquery .GET function from JSON data

The jQuery below illustrates how I get the products from https://dummyjson.com/products. However, I don't know how to iterate the loop to retrieve each of the 30 products in the link and the details of each product.
$.get("https://dummyjson.com/products/1")
.done(function(data, textStatus, jqXHR){
console.log("typeof(data) is: " + typeof(data));
console.log("data is: "+ data);
console.log(data.length);
var result = [];
result = JSON.parse(JSON.stringify(data));
console.log(typeof(result));
console.log(result.length);
var keys = Object.keys(result);
keys.forEach(function (key) {
console.log("forEach");
console.log(key, result[key]);
//console.log(result[0]);
});
})
.fail(function(jqXHR, textStatus, errorThrown){
alert("error");
console.log(jqXHR);
console.log(textStatus);
console.log(errorThrown);
});
You should iterate through the object itself instead of the keys. Also, use let instead of var (see here).
$.get("https://dummyjson.com/products/1")
.done(function(data) {
let result = JSON.parse(JSON.stringify(data));
$.each( result, function( key, value ) {
console.log( key + ": " + value );
});
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
For multiple products you need another for loop to iterate through each product:
$(document).ready(function() {
$.get("https://dummyjson.com/products")
.done(function(data) {
let result = JSON.parse(JSON.stringify(data));
$.each(result, function( key, products) {
for (let i = 0; i < products.length; ++i) {
console.log(products[i].id);
console.log(products[i].title);
console.log(products[i].description);
}
});
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Thats is totally depends upon how was your reponse are.
If your response like this.
{
"status": true,
"data" : [
{
"id": 1,
"name": "xyz",
},
{
"id": 2,
"name": "xyz",
}
]
}
then you have to use following code:
$.get('/your-url', function(response) {
if(response.status) {
$.each(response.data, function(index, item) {
console.log(item);
})
} else {
alert('Your API sent false status')
}
})
Otherwise your response something like this.
[
{
"id": 1,
"name": "xyz",
},
{
"id": 2,
"name": "xyz",
}
]
then you have to use following code:
$.get('/your-url', function(response) {
$.each(response, function(index, item) {
console.log(item);
})
})

How to access a nested key in json using javascript

So, i have this json file, in which i have to take out the fileName tag, and use it.
{
"dataset": {
"private": false,
"stdyDscr": {
"citation": {
"titlStmt": {
"titl": "Smoke test",
"IDNo": {
"text": "10.5072/FK2/WNCZ16",
".attrs": {
"agency": "doi"
}
}
},
"rspStmt": {
"AuthEnty": "Dataverse, Admin"
},
"biblCit": "Dataverse, Admin, 2015, \"Smoke test\", http://dx.doi.org/10.5072/FK2/WNCZ16, Root Dataverse, V1 [UNF:6:iuFERYJSwTaovVDvwBwsxQ==]"
}
},
"fileDscr": {
"fileTxt": {
"fileName": "fearonLaitinData.tab",
"dimensns": {
"caseQnty": "6610",
"varQnty": "69"
},
"fileType": "text/tab-separated-values"
},
"notes": {
"text": "UNF:6:K5wLrMhjKoNX7znhVpU8lg==",
".attrs": {
"level": "file",
"type": "VDC:UNF",
"subject": "Universal Numeric Fingerprint"
}
},
".attrs": {
"ID": "f6"
}
}
},
im using d3.js mostly, but some parts of jquery and javascript with it. right now im doing:
d3.json(url,function(json){
var jsondata=json;
var temp = jsondata.dataset.fileDscr.fileTxt.fileName;
}
Is there a way to just access fileName directly? Im asking because, i have to make this generic to fit other json files, where the nesting might be different.
This will return the value for some instance of the key in the JSON data, if it exists.
var data = {...};
function findValue(json, key) {
if (key in json) return json[key];
else {
var otherValue;
for (var otherKey in json) {
if (json[otherKey] && json[otherKey].constructor === Object) {
otherValue = findValue(json[otherKey], key);
if (otherValue !== undefined) return otherValue;
}
}
}
}
console.log(findValue(data, 'fileName'));
It will return a comma separated string of all the values of a specified key
function walk(obj,keyname) {
var propertyVal="";
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
var val = obj[key];
if(typeof(val) == 'object') {
console.log(val);
propertyVal+= walk(val,keyname);
}else {
if(key == keyname){
propertyVal = propertyVal+","+obj[key];
}
}
}
}
return propertyVal;
}
alert(walk(data,'filename').replace(',',''));

Covert object to array of combinations/objects

Using lodash or underscore. I'm trying to convert this object:
{
"variations": {
"versions": ["sport", "generic"],
"devices": ["mobile", "tablet"]
}
}
to this:
var variations = [{
"version": "sport",
"device": "mobile"
}, {
"version": "sport",
"device": "tablet"
}, {
"version": "generic",
"device": "mobile"
}, {
"version": "generic",
"device": "tablet"
}];
What's the best/shortest method to do this?
Not sure with lodash or undesrcore. But with simple jquery i have done this. take a look.
var object={
"variations": {
"versions": ["sport", "generic"],
"devices": ["mobile", "tablet"]
}
};
var variations=[];
$.each(object.variations.versions, function(i, j) {
$.each(object.variations.devices, function(k, l) {
variations.push({version:j,device:l});
});
});
I think you wanna set object key to new variable name and do combinations of inside object values.
<script type="text/javascript">
//here I created two object keys for more clear
var json ={
"variations": {
"versions": ["sport", "generic"],
"devices": ["mobile", "tablet"]
},
"another_variations": {
"versions": ["sport", "generic"],
"devices": ["mobile", "tablet"]
}
};
for(var i in json){
window[i] = []; //here window[variable] will make global variable
ver = Object.keys(json[i])[0];//Object.keys(json[i]) get object keys ~["versions","devices"]
dev = Object.keys(json[i])[1];
window[i].push(
{
[ver]:json[i].versions[0],
[dev]:json[i].devices[0]
},
{
[ver]:json[i].versions[0],
[dev]:json[i].devices[1]
},
{
[ver]:json[i].versions[1],
[dev]:json[i].devices[0]
},
{
[ver]:json[i].versions[1],
[dev]:json[i].devices[1]
});
}
console.log(variations); //here can call object key as a variable name if you
console.log(another_variations);//don't use `window[variable]` in above, this will print undefined error
</script>
Found a solution using: https://gist.github.com/wassname/a882ac3981c8e18d2556
_.mixin({
cartesianProductOf: function(args) {
if (arguments.length > 1) args = _.toArray(arguments);
// strings to arrays of letters
args = _.map(args, opt => typeof opt === 'string' ? _.toArray(opt) : opt)
return _.reduce(args, function(a, b) {
return _.flatten(_.map(a, function(x) {
return _.map(b, function(y) {
return _.concat(x, [y]);
});
}), true);
}, [
[]
]);
},
cartesianProductObj: function(optObj) {
var keys = _.keys(optObj);
var opts = _.values(optObj);
var combs = _.cartesianProductOf(opts);
return _.map(combs, function(comb) {
return _.zipObject(keys, comb);
});
}
});
See working:
https://jsfiddle.net/rickysullivan/5ryf9jsa/

Creating an array in JavaScript from JSON file

My JSON file:
[{"val0":"Paul","val1":"Jake","val2":null,"val3":"Max"},
{"val0":"Sam","val1":"Tina","val2":"Emily","val3":"Hardwell"},
{"val0":"Tom","val1":"Julie","val2":null,"val3":"Adi"}]
I want to create an array in javascript as follows:
var dataSet=[
['Paul','Jake','null','Max'],
['Sam','Tina','Emily','Harwell'],
['Tom','Julie','null','Adi']
];
I tried the following code but it isn’t working. Can anybody please help?
$.getJSON("filename.json", function(data) {
var items = [];
$.each(data, function(key, val) {
items.push(val);
});
// …
});
I’m using this array for display purpose (using DataTables), so, I want to create the array in that format.I'm using the dataSet array for displaying in DataTables as follows:
var dataSet = [
['Paul','Jake','Isha','Mike','null','null','Parth','Tinker'],
['Tina','Michael','null','Blue','Red','','Emily','Mina']
];
$(document).ready(function() {
$('#demo').html( '<table cellpadding="0" cellspacing="0" border="0" class="display" id="example"></table>' );
$('#example').dataTable( {
"data": dataSet,
"columns": [
{ "title": "Name" },
{ "title": "Deadline" },
{ "title": "Additional fees" },
{ "title": "Requirements" },
{ "title": "Field" },
{ "title": "Award" },
{ "title": "Renewable requirements"},
{ "title": "Link" }
]
} );
} );
You get an array of objects, and you want an array of arrays, so convert each object to an array by reading the properties of the object:
var items = [];
$.each( data, function( key, val ) {
items.push([val.val0,val.val1,val.val2,val.val3]);
});
Try this
<script>
$(function() {
$.getJSON("filename.json", function(data) {
var items = [];
$.each(data, function(key, val) {
var tmp = [];
for (var Key in val) {
tmp.push(val[Key]);
}
items.push(tmp);
});
console.log(items);
});
});
A solution without jquery:
var data = [
{ "val0": "Paul", "val1": "Jake", "val2": null, "val3": "Max" },
{ "val0": "Sam", "val1": "Tina", "val2": "Emily", "val3": "Hardwell" },
{ "val0": "Tom", "val1": "Julie", "val2": null, "val3": "Adi" }
],
dataSet = data.reduce(function (r, a) {
var i, a0 = [];
for (i in a) {
a0.push(a[i]);
}
r.push(a0);
return r;
}, []);
document.getElementById('out').innerHTML = JSON.stringify(dataSet, null, 4);
<pre id="out"></pre>
One liner:
var dataSet = rawData.map(function(e){ return Object.keys(e).map(function(i){ return e[i]}); })
Output:
Output as JSON:
Method explanation (from Javascript Reference)
The map() method creates a new array with the results of calling a provided function on every element in this array.
The Object.keys() method returns an array of a given object's own enumerable properties

Starting at a specific index in each function

Please take a look at this fiddle
How can I use slice in the loop to make it return results starting from a specific index?
The JSON file:
[
{
"title": "A",
"link": "google.com",
"image": "image.com",
"price": "$1295.00",
"brand": "ABC",
"color": "Black",
"material": "Rubber"
}
]
I want it to return results starting from brand:
brand - ABC
color - Black
material - Rubber
I don't know where to put .slice(4) in the loop. I got undefined error using
$.each(value.slice(4),function(key, value)
Here's the code:
JS:
$.ajax({
url: "https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20json%20where%20url%20%3D%22http%3A%2F%2Fgoo.gl%2FaZgYDB%22&format=json&diagnostics=true&callback=",
success: function (data) {
var item_html="";
$(data.query.results.json).each(function(key, value) {
$.each(value,function(key, value){
item_html += '<h3>'+key+' - '+value+'</h3>';
});
});
$('#area').append(item_html);
}
});
Use a separate array of property names, so you can slice it and get the names in a guaranteed order.
var props = [
"title",
"link",
"image",
"price",
"brand",
"color",
"material"
];
$.ajax({
url: "https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20json%20where%20url%20%3D%22http%3A%2F%2Fgoo.gl%2FaZgYDB%22&format=json&diagnostics=true&callback=",
dataType: 'json',
success: function (data) {
var item_html="";
var propslice = props.slice(4);
$.each(data.query.results.json, function(i, obj) {
$.each(propslice, function(i, key) {
value = obj[key];
item_html += '<h3>'+key+' - '+value+'</h3>';
});
});
$('#area').append(item_html);
}
});
If there are a small number of properties you want to skip, you can make a list of them in an object, and test against that list:
var excluded_props = {
title: true,
link: true,
image: true,
price: true
};
$.ajax({
url: "https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20json%20where%20url%20%3D%22http%3A%2F%2Fgoo.gl%2FaZgYDB%22&format=json&diagnostics=true&callback=",
dataType: 'json',
success: function (data) {
var item_html="";
$.each(data.query.results.json, function(i, obj) {
$.each(obj, function(key, value) {
if (!excluded_props[key]) {
value = obj[key];
item_html += '<h3>'+key+' - '+value+'</h3>';
}
});
});
$('#area').append(item_html);
}
});
What you're asking for isn't possible with an object. Objects in Javascript are not ordered, only arrays. You have a few options:
Refactor your object to be an array
Refactor your object so that each key has a new key for order*
loop through each property of the object, placing it into an array (no guaranteed order!) and then looping through the array.
*Example:
[
{
"title": {
"value" : "A",
"order" : 4
},
"link": {
"value" : "google.com",
"order" : 5
...
}
]

Categories

Resources