Parse Nested JSON using jquery & Ajax - javascript

found a code snippet i am trying to modify but i can't seem to get it to work, This code is made to parse the json format as such
[
{
"name":"Barot Bellingham",
"shortname":"Barot_Bellingham",
"reknown":"Royal Academy of Painting and Sculpture",
"bio":"Barot has just finished his final year at The Royal Academy of Painting and Sculpture, where he excelled in glass etching paintings and portraiture. Hailed as one of the most diverse artists of his generation, Barot is equally as skilled with watercolors as he is with oils, and is just as well-balanced in different subject areas. Barot's collection entitled \"The Un-Collection\" will adorn the walls of Gilbert Hall, depicting his range of skills and sensibilities - all of them, uniquely Barot, yet undeniably different"
}
]
and my json format is multilevel nested such as
{
"data": [
{
"artists": {
"Artist": "Muse"
}
},
{
"artists": {
"Artist": "Coldplay"
}
}
]
}
The Javascript i found is
$('#search').keyup(function(){
var searchField = $('#search').val();
var myExp = new RegExp(searchField, 'i');
$.getJSON('data.json', function(data){
var output = '<ul class="searchresult">';
$.each(data, function(key, val){
if((val.name.search(myExp) != -1) || (val.bio.search(myExp) != -1)) {
output +='<li>';
output +='<h2>' + val.name + '</h2>';
output +='<img src="images/' + val.shortname + '_tn.jpg" alt="'+ val.name +'" />';
output +='<p>' + val.bio + '</p>';
output +='</li>';
}
});
output += '</ul>';
$('#update').html(output);
});
});
So how and where would i modify this to sort through my json format?
Thanks!

The response data is an object with a property data that contains an array, which you should loop over with $.each(). Each element is an object with an artists property, and its value is an object with an Artist property (I don't know why they have this extra level of nesting, it seems redundant).
$.each(data.data, function(index, val) {
var artist = val.artists.Artist;
// do what you want with artist
});

Related

Convert nested json to CSV with keys javascript

All
I am trying to convert nested JSON into CSV with object key as group identifier in csv.
this is the JSON I am working on
"Name": "Name",
"LoyaltyNumber": "Loyalty Number",
"LoyaltySaved": "Loyalty Items Were Saved",
"LoyaltyDeleted": "Loyalty Item Was Deleted",
"Add": "Add ",
"Loyalty": " Loyalty",
"DeleteLoyalty": "Delete Loyalty"
},
"LoyaltyViewer": {
"AirlineLoyalty": "Airline Loyalty",
"HotelLoyalty": "Hotel Loyalty",
"CarLoyalty": "Car Loyalty",
"RailLoyalty": "Rail Loyalty"
},
my current script for conversion is
function toCSV(json) {
json = Object.values(json);
let csv = '';
const keys = (json[0] && Object.keys(json[0])) || [];
csv += keys.join(',') + '\n';
for (let line of json) {
csv += keys.map((key) => line[key]).join(',') + '\n';
}
FileSystem.writeFileSync('./destination3.csv', csv);
return csv;
}
but the result is not what is expected result should be similar to this
expected
but i am getting it like this
result
Can you please point me in a right direction , Thanks
you can use papa parse this one is a very powerful tool to handle csv and json data
https://www.papaparse.com/docs#json-to-csv
it has npm and cdn both.

How to Convert JSON Data into HTML

I came across an exercise in freeCodeCamp to convert json data to html. Here, I was asked to copy paste a jquery which I didn't understand.
json.forEach(function(val) {
var keys = Object.keys(val);
html += "<div class = 'cat'>";
keys.forEach(function(key) {
html += "<strong>" + key + "</strong>: " + val[key] + "<br>";
});
html += "</div><br>";
});
This is my json
[
{
"id":0,
"imageLink":"https://s3.amazonaws.com/freecodecamp/funny-cat.jpg",
"altText":"A white cat wearing a green helmet shaped melon on it's head. ",
"codeNames":[
"Juggernaut",
"Mrs. Wallace",
"Buttercup"
]
},
{
"id":1,
"imageLink":"https://s3.amazonaws.com/freecodecamp/grumpy-cat.jpg",
"altText":"A white cat with blue eys, looking very grumpy. ",
"codeNames":[
"Oscar",
"Scrooge",
"Tyrion"
]
},
{
"id":2,
"imageLink":"https://s3.amazonaws.com/freecodecamp/mischievous-cat.jpg",
"altText":"A ginger cat with one eye closed and mouth in a grin-like expression. Looking very mischievous. ",
"codeNames":[
"The Doctor",
"Loki",
"Joker"
]
}
]
Can anyone help me to break down this code and tell what each line in the code does? For example I don't know what Object.keys does. Is Object an inbuilt instance?
The Object.keys() method returns an array of a given object's own enumerable properties.
var keys = Object.keys(val);
Here 'keys' is the array form of your json.
According to the JSON you provided the array has 3 objects.
You can also write
Object.keys(val).forEach(function(key){
//something
});
instead of
var keys = Object.keys(val);
keys.forEach(function(key) {
//something
});
Inside the loop the key returns the the key of your object i.e.
id, imageLink etc
and
val[key] return corresponding values e.g.
0, "https://s3.amazonaws.com/freecodecamp/funny-cat.jpg" to be more specific.
From MDN
Object.keys() returns an array whose elements are strings corresponding to the enumerable properties found directly upon object. The ordering of the properties is the same as that given by looping over the properties of the object manually.
The purpose of the code is to generate html by using key and corresponding value.
var json = [
{
"id":0,
"imageLink":"https://s3.amazonaws.com/freecodecamp/funny-cat.jpg",
"altText":"A white cat wearing a green helmet shaped melon on it's head. ",
"codeNames":[
"Juggernaut",
"Mrs. Wallace",
"Buttercup"
]
},
{
"id":1,
"imageLink":"https://s3.amazonaws.com/freecodecamp/grumpy-cat.jpg",
"altText":"A white cat with blue eys, looking very grumpy. ",
"codeNames":[
"Oscar",
"Scrooge",
"Tyrion"
]
},
{
"id":2,
"imageLink":"https://s3.amazonaws.com/freecodecamp/mischievous-cat.jpg",
"altText":"A ginger cat with one eye closed and mouth in a grin-like expression. Looking very mischievous. ",
"codeNames":[
"The Doctor",
"Loki",
"Joker"
]
}
]
var html = "";
//iterating through all the item one by one.
json.forEach(function(val) {
//getting all the keys in val (current array item)
var keys = Object.keys(val);
//assigning HTML string to the variable html
html += "<div class = 'cat'>";
//iterating through all the keys presented in val (current array item)
keys.forEach(function(key) {
//appending more HTML string with key and value aginst that key;
html += "<strong>" + key + "</strong>: " + val[key] + "<br>";
});
//final HTML sting is appending to close the DIV element.
html += "</div><br>";
});
document.body.innerHTML = html;

list of strings from array to variable name

I'm grabbing a list of elements ids thusly.
var menus = $(".menu").map(function(){
return this.id;
});
Which returns something like:
["lunch", "appetizers", "soup", "salads", "seafood", "noodles", "stir_fry", "curry", "kids", "steak", "dessert", "sides"]
For each item in the array I want to grab some JSON data.
$.each(menus,function(i) {
var list = menus[i],
meal = data.menu.list,
items = '<li><h3>' + meal.name + '</h3><p>' + meal.desc + '</p></li>';
$('#'+list+".menu").append(items);
});
Such that data.menu.list would be data.menu.lunch, data.menu.appetizers, etc.
The JSON is structured like so:
{
"menu": {
"lunch": [{
"name": "Kao PAdd",
"desc": "Fried rice with onions, green onions, snow peas, and egg / Chicken, vegetarian / Shrimp or tofu (Add $1)"
}
Any thoughts that don't involve eval()?
EDIT:
I when I do this:
$.each(data.menu,function(i) {
console.log(data.menu[i].key);
});
the console gives me:
Object {lunch: Array(14), appetizer: Array(11)}
All I really want is to access those arrays.
console.log(data.menu[i].name)
gives me a pair of undefineds.
That’s a brilliant question, Sir!
No matter how you retrieve your menus, strToVar() will do the task.
This code converts strings from array to variable names:
Solution:
var strToVar = (str,val) => this[str] = val;
Example:
var menus = ["lunch", "appetizers", "soup", "salads", "seafood", "noodles",
"stir_fry", "curry", "kids", "steak", "dessert", "sides"];
menus.forEach(strToVar);
prompt("[lunch, appetizers, soup, salads, seafood, noodles, " +
"stir_fry, curry, kids, steak, dessert, sides]",
[lunch, appetizers, soup, salads, seafood, noodles,
stir_fry, curry, kids, steak, dessert, sides]);
Give me all your points.
If you're looking for parsing JSON string to object here you go:
var jsonString = '{"data":{"item":{"id":1,"value":"foo"}}}';
var jsonObj = JSON.parse(jsonString);
console.log(jsonObj.data.item.value);
The problem was, I didn't understand what I really wanted to do. I asked the wrong question (although it's an interesting one, so I'll leave it up).
I thought I needed to generate my variable list from the HTML ids, but that was a mistake. What I needed was simply another for loop (or jQuery each());
$.each(data.menu, function(i) {
var list = data.menu[i],
menus = [];
$.each(list, function(x) {
var items = '<li><h3>' + list[x].name + '</h3><p>' + list[x].desc + '</p></li>';
menus.push(items)
});
$('#' + i).append(menus);
});
Your $.each function should be:
$.each(menus, function(i, list) { // the second parameter is list so we don't need menus[i]
var meal = data.menu[list], // use of bracket notation
items = '<li><h3>' + meal.name + '</h3><p>' + meal.desc + '</p></li>';
$('#' + list).append(items);
// ^^^ no need for the ".menu" as IDs alone are sufficient (assuming you have unique IDs, otherwise you have a problem)
});
Docs on MDN for bracket notation.
As per my understanding you want to achieve something like this :
var menus = ["lunch", "appetizers", "soup", "salads"];
var menuList = [
{
"name":"lunch",
"description":"description1"
},
{
"name":"appetizers",
"description":"description2"
},
{
"name":"soup",
"description":"description3"
},
{
"name":"salads",
"description":"description4"
}
]
var menu = {};
for(var i in menus) {
menu[menus[i]] = [{
"name": menuList[i].name,
"desc": menuList[i].description
}];
}
console.log(menu);

Parse nested JSON

I have the following JSON on a URL:
{
"href":"http:\/\/api.rwlabs.org\/v1\/jobs?limit=10",
"time":18,
"links":
{
"self":
{
"href":"http:\/\/api.rwlabs.org\/v1\/jobs?offset=0&limit=10&preset=minimal"
},
"next":
{
"href":"http:\/\/api.rwlabs.org\/v1\/jobs?offset=10&limit=10&preset=minimal"
}
},
"totalCount":2279,
"count":10,
"data":[
{
"id":"1148141",
"score":1,
"href":"http:\/\/api.rwlabs.org\/v1\/jobs\/1148141",
"fields":
{
"title":"Volunteer Renewable Energy Programmes Coordinator"
}
},
{
"id":"1147901",
"score":1,
"href":"http:\/\/api.rwlabs.org\/v1\/jobs\/1147901",
"fields":
{
"title":"Volunteer Project Management Coordinators \/ Intern"
}
}
/* so on*/
And I want get the information inside "data" and inside "fields".
If I remove the part before data array, I can get some of the values, but fields returns undefined. Although I also need to have a solution without removing the information before data.
JS
var table = '<table><thead><th>id</th><th>title</th></thead><tbody>';
var obj = $.parseJSON(data);
$.each(obj, function(i, val) {
table += '<tr><td>' + this['id'] + '</td><td>' + this['obj[i].title'] + '</td></tr>';
});
table += '</tbody></table>';
document.getElementById("datalist").innerHTML = table;
(I also do not know how to parse the data from the URL, so for now I am copying the data into the script)
[JSFiddle]: http://jsfiddle.net/1v803c3L/1/ Although I have part of the data on the code, even though the entire information is on an URL as seen on the code I posted.
obj.data[i].fields.title where i is an int that you use to index into the data array

JSON assistance

So I am looking for a little bit of guidance, tips and knowledge transfer. Currently I am practicing fetching JSON data, but I am having some issues.
My current problem I a running into is that my 3 variable (brand, desc and price) give me this error: Uncaught TypeError: Cannot read property 'Brand' of undefined
Can someone help me with this, also tips on better coding would be nice.
var url = 'https://raw.githack.com/gromstone/jsonFiles/master/products.json';
$.ajax({
type: 'GET',
dataType: 'json',
url: url,
success: function(data){
console.log(data);
$.each(data, function(i, products){
var content = "<div class=\"item grid_4\">";
$.each(products, function(i, mainProd){
var brand = mainProd.ProductInfo.Brand,
desc = mainProd.ProductInfo.p_product_description,
price = mainProd.ProductInfo.p_product_price;
//content += '<img class="scale-with-grid" src="' + src + '"/>';
content += '<p>' + brand + desc + '</p>';
content += '<p>' + price + '</p>';
content += '<a>View More</a>';
});
content += "</div><!-- product -->";
$('.load').append(parent);
})
},
error: function(){
alert('Data did not load, or no connection')
}
});
You can see working code here:
http://jsfiddle.net/gromstone/j1etxuw0/1/
Also if anyone can provide additional help, I want to make a hover effect for each one of the 'div.items' where some additional data is shown on a separate div (ex 'div.placeHolder')
Thanks!
The problem seems to be that you're looping over all properties of the object that your receive in the outer loop
$.each(data, function(i, products){
and in the inner loops you're expecting these properties to be arrays, and each array member to have a ProductInfo property:
$.each(products, function(i, mainProd){
var brand = mainProd.ProductInfo.Brand,
However, the top-level properties of your JSON document are:
[
"ProductsList",
"RecordsCount",
"nValue",
"Pages",
"Refinements",
"Breadcrumbs",
"CategoryName",
"sortProperty"
]
So your program will first loop over the internals of ProductsList (what I guess is what you expected it to do), but after that, it will loop over the contents of RecordsCount, which in the JSON you linked does not contain an array but the number 8. The inner loops in your program however expect it to be an array, and they will try to access a property ProductInfo of the (non-array) members, which will then fail with an error.
If you're only after iterating over the ProductsList of the JSON, removing the outer loop, and change the remaining (formerly inner) loop's each to:
$.each(data.ProductsList, function(i, mainProd){

Categories