Related
First time being exposed to JSON so please explain like I'm 5 without the jargon.
I have been given a JSON file like this and need to display these items in a list in HTML.
A lot of examples have the JSON object assigned to a variable- this isn't assigned to a variable so I'm unsure how to reference it.
How can I access and display everything in product list.
In my html I have linked to a script.js file and also this json file.
HTML
<h1>My Cart</h1>
<div id="cart">
<h2>Cart Items</h2>
<ul id="cartItemsList">
</ul>
</div>
JSON
"basket": {
"productList": [{
"product": {
"id": "111",
"name": "Dog",
"shortDescription": "<p>Mans best friend</p>",
},
"category": "Canine",
"availability": "In Stock",
"variationType": {
"name": "Breed",
"value": "Collie"
}
},
"quantity": 1,
"price": "$53.00"
}, {
"product": {
"id": "112",
"name": "Dog",
"shortDescription": "<p>Not so best friend</p>",
"category": "feline",
"availability": "Low In Stock",
"variationType": {
"name": "breed",
"value": "Maine Coon"
}
},
"quantity": 1,
"price": "$49.00"
}, {
"product": {
"id": "113",
"name": "Rabbit",
"shortDescription": "Likes carrots",
"category": "cuniculus",
"availability": "In Stock"
},
"quantity": 1,
"price": "$66.00"
}]
}
JavaScript
var products = document.getElementById("cartItemsList");
cartItemsList.innerHTML = "<li>" + product + "</li>";
If you are loading this from an external file, you will need Ajax or a similar type of call. To use Ajax, you'll have to add a library called jQuery to your project's HTML file. Then you can call your JSON without referencing it as a javascript variable as you see in the following working code snippet.
/* I put your JSON into an external file, loaded from github */
var url = "https://raw.githubusercontent.com/mspanish/playground/master/jessica.json";
/* this tells the page to wait until jQuery has loaded, so you can use the Ajax call */
$(document).ready(function(){
$.ajax({
url: url,
dataType: 'json',
error: function(){
console.log('JSON FAILED for data');
},
success:function(results){
/* the results is your json, you can reference the elements directly by using it here, without creating any additional variables */
var cartItemsList = document.getElementById("cartItemsList");
results.basket.productList.forEach(function(element) {
cartItemsList.insertAdjacentHTML( 'beforeend',"<li>" + element.product.name + " : " + element.price+ " </li>");
}); // end of forEach
} // end of success fn
}) // end of Ajax call
}) // end of $(document).ready() function
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1>My Cart</h1>
<div id="cart">
<h2>Cart Items</h2>
<ul id="cartItemsList">
</ul>
</div>
if you want to parse an object:
function logTheObj(obj) {
var ret = "";
for (var o in obj) {
var data = obj[o];
if (typeof data !== 'object') {
ret += "<li>" + o + " : " + data + "</li>";
} else {
ret += "<li>" + o + " : " + logTheObj(data) + "</li>";
}
}
return "<ul>" + ret + "</ul>";
}
If your object is in a string:
logTheObj(JSON.parse(jsonString));
JavaScript version using external json file from previous answer by Stacey Reiman
const products = document.getElementById("cartItemsList");
/* get basket items from JSON */
class Basket {
async cartItems() {
try {
let result = await fetch('https://raw.githubusercontent.com/mspanish/playground/master/jessica.json')
let data = await result.json()
// return data
/* destructuring data */
let basketItems = data.basket.productList
basketItems = basketItems.map(item =>{
const price = item.price
const{id,name,shortDescription,category,availability} = item.product
const breed = item.product.variationType
const quantity = item.quantity
return {price,id,name,shortDescription,category,availability,quantity,breed}
})
return basketItems
} catch (error) {
console.log(error)
}
}
}
/* Display stuff from the basket */
class Display {
displayBasket(basket) {
//console.log(basket)
let result = ""
basket.forEach((item)=>{
result += `
<li>
id : ${item.id}
name: ${item.name}
price: ${item.price}
availability: ${item.availability}
category : ${item.category}
quantity : ${item.quantity}
shortDescription : ${item.shortDescription}
</li>
`})
cartItemsList.innerHTML = result
}
}
document.addEventListener("DOMContentLoaded", ()=>{
const basket = new Basket()
const display = new Display()
basket.cartItems().then(basket => display.displayBasket(basket))
})
<h1>My Cart</h1>
<div id="cart">
<h2>Cart Items</h2>
<ul id="cartItemsList">
</ul>
</div>
First, you have to convert the json from long string to acutely js object.
you doing so by the JSON.parse command. like so:
let jsObj = JSON.parse( youreJsonString);
Them, you can loop throw youre products in your productList and build your html code, like so:
var products = document.getElementById("cartItemsList");
jsObj.basket.productList.forEach( function(product ) {
cartItemsList.innerHTML = "<li>" + product.name + " : " + product.price+ " </li>";
});
Unless you use an Ajax call or something similar to load external JSON, you need to convert the JSON you've provided into an object that you can reference as a variable. Also, your JSON is not valid. I tried correcting it here, and am going to reference your JSON as an object you can reference via a variable named obj. Here is a working code snippet.
var obj = {
"basket": {
"productList": [{
"product": {
"id": "111",
"name": "Dog",
"shortDescription": "<p>Mans best friend</p>",
"category": "Canine",
"availability": "In Stock",
"variationType": {
"name": "Breed",
"value": "Collie"
}
},
"quantity": 1,
"price": "$53.00"
}, {
"product": {
"id": "112",
"name": "Dog",
"shortDescription": "<p>Not so best friend</p>",
"category": "feline",
"availability": "Low In Stock",
"variationType": {
"name": "breed",
"value": "Maine Coon"
}
},
"quantity": 1,
"price": "$49.00"
}, {
"product": {
"id": "113",
"name": "Rabbit",
"shortDescription": "Likes carrots",
"category": "cuniculus",
"availability": "In Stock"
},
"quantity": 1,
"price": "$66.00"
}]
}
}
var cartItemsList = document.getElementById("cartItemsList");
obj.basket.productList.forEach(function(element) {
cartItemsList.insertAdjacentHTML( 'beforeend',"<li>" + element.product.name + " : " + element.price+ " </li>");
});
<h1>My Cart</h1>
<div id="cart">
<h2>Cart Items</h2>
<ul id="cartItemsList">
</ul>
</div>
I have a json response containing one array, inside that array I have one more array.
My AJAX:
$.ajax({
type: "POST",
data: { city: city, priceRange: range },
url: "rentpriceRangeFilter.php",
success: function(data) {
var res = jQuery.parseJSON(data); // convert the json
console.log(res);
if (res['status'] == 1) {
var htmlString = '';
$.each(res['data'], function(key, value) {
console.log(key + ' is ' + value.house);
});
}
},
});
rentpriceRangeFilter.php (I return the json response)
echo json_encode(array("status"=>"1","response"=>"success","data"=>$mainArray));
My JSON response like this:
{
"status": "1",
"response": "success",
"data": [{
"id": "2",
"house": "1 BHK Apartment for Lease",
"rentLease_amount": "6000000",
"furnished_type": "Semi-Furnished",
"CreatedOn": null,
"Rent": "60 Lac",
"multipleImages": [{
"imageId": "3",
"rentImageId": "2",
"rentImageName": "2cf011438e6cd43c6bfaa6cac653d86e.jpg"
}, {
"imageId": "4",
"rentImageId": "2",
"rentImageName": "e2c5be420130370c5118120a1bc749c6.jpg"
}]
}, {
"id": "1",
"house": "1 BHK Aparatment for Marathahalli",
"rentLease_amount": "500000",
"furnished_type": "Fully-Furnished",
"CreatedOn": null,
"Rent": "5 Lac",
"multipleImages": [{
"imageId": "1",
"rentImageId": "1",
"rentImageName": "7d2905c30ab211732b97dbf165c75526.jpg"
}, {
"imageId": "2",
"rentImageId": "1",
"rentImageName": "bcf6cb343aaa2cc8e50ff52baa062bcc.jpg"
}]
}]
}
Now I want to display house name and multipleImages values, but in my ajax page I can get only house name, I don't how to display the multipleImages.
You can use another loop on multipleImages like below:
$.ajax({
type: "POST",
data: {city:city,priceRange:range},
url: "rentpriceRangeFilter.php",
success:function(data){
var res=jQuery.parseJSON(data);// convert the json
console.log(res);
if(res['status']==1){
var htmlString='';
$.each( res['data'], function( key, value ) {
console.log(key + ' is ' + value.house);
$.each( value.multipleImages, function( key2, image ) {
console.log('imageId of ' + key2 + ' is ' + image.imageId);
console.log('rentImageId of ' + key2 + ' is ' + image.rentImageId);
console.log('rentImageName of ' + key2 + ' is ' + image.rentImageName);
});
});
}
},
});
You can loop again through your properties :
Here's a jsfiddle demonstrating the solution : https://jsfiddle.net/equbq6rf/
const data = [{
"house":"My house",
"multipleImages":[{
"imageId":1,
"rentImageId":2,
"rentImageName":"image_name.jpg"
},{
"imageId":3,
"rentImageId":4,
"rentImageName":"image_name2.jpg"
}]
},{
"house":"My house number 3",
"multipleImages":[{
"imageId":5,
"rentImageId":6,
"rentImageName":"image_name3.jpg"
},{
"imageId":7,
"rentImageId":8,
"rentImageName":"image_name4.jpg"
}]
}];
$.each(data, (key, value) => {
console.log(key + ' is ' + value.house);
$.each(value['multipleImages'], (imageKey, imageValue) => {
Object.keys(imageValue).forEach((property) => {
console.log(imageValue[property]);
});
});
});
You can push it further but it should do the trick.
Hope it helps :)
Dylan
I have this below type of array. I want to iterate this array in JavaScript. How is this possible?
{
"result": true,
"data": [
{
"ID": 1,
"stage_ID": 1,
"badge_type_ID": 1,
"name": "Despertar da Força",
"description": "Fazer a primeira SuperAtividade",
"type": "",
"image_static": "url123.jpg",
"image_animated": "",
"SQL": "",
"published": 1
},
{
"ID": 2,
"stage_ID": 1,
"badge_type_ID": 1,
"name": "Super 3",
"description": "Fazer 3 SuperAtividades",
"type": "",
"image_static": "urlimage123.png",
"image_animated": "",
"SQL": "",
"published": 1
}
etc
I tried the following script and it is returning "undefined", "undefined".
$.getJSON('https://www.legiaodossuperpoderes.com.br/chronus/api/adm/badges', function(data) {
var output= "<ol>";
for (var i in data) {
output += "<li>" + data[i].ID + "</li>"
}
output+="</ol>";
document.getElementById("placeholder").innerHTML=output;
});
Any solutions ? Thanks!
You can try converting to Json Object
$.getJSON('https://www.legiaodossuperpoderes.com.br/chronus/api/adm/badges', function(data) {
var output= "<ol>";
var jsondata = $.JSON.parse(data); // Json object Convertion
for (var i in data) {
output += "<li>" + data[i].ID + "</li>"
}
output+="</ol>";
document.getElementById("placeholder").innerHTML=output;
});
You are trying to access an undefined property using data[i].ID .
When you are getting response from your getJSON() function then you need to call the response with a name and then you can access any inner property using this name .
Now if you want to iterate using data key/value on myResponse variable then you need to do this.
$.getJSON('https://www.legiaodossuperpoderes.com.br/chronus/api/adm/badges', function(myResponse) {
var output= "<ol>";
var dataCount = myResponse.data.length;
for (var i = 0; i < dataCount; i++) {
output += "<li>" + myResponse.data[i].ID + "</li>";
}
output+="</ol>";
document.getElementById("placeholder").innerHTML=output;
});
I am getting jsonString object in my ajax call.can any one tell me how to print this object as a dropdown .
[
{
"id" : 3272,
"name" : "a"
},
{
"id" : 3255,
"name" : "b"
},
{
"id"
: 3257,
"name" : "c"
},
{
"id" : 3253,
"name" : "d"
},
{
"id" : 3256,
"name" : "e"
}
]
That's my code:
<script>
$(document).ready(function() {
$("#customerDetails").change(function() {
var value = $('#customerDetails :selected').text();
$.ajax({
type: 'GET',
url: 'environments',
data: {
selectedcustomername: value
},
success: function(result) { //this result is my jsonstring object alert("success");
}
});
});
});
</script>
Let say myJson is
{
"myJson": [
{
"id": 3272,
"name": "a"
},
{
"id": 3255,
"name": "b"
},
{
"id": 3257,
"name": "c"
},
{
"id": 3253,
"name": "d"
},
{
"id": 3256,
"name": "e"
}
]
}
var options = eval(myJson);
Using jQuery to fill options
var length = options.length;
for(var j = 0; j < length; j++)
{
var newOption = $('<option/>');
newOption.attr('text', options[j].name);
newOption.attr('value', options[j].id);
$('#mySelect').append(newOption);
}
Also have a look here
var row=[{"id":3272,"name":"a"},{"id":3255,"name":"b"},{"id"
:3257,"name":"c"},{"id":3253,"name":"d"
},{"id":3256,"name":"e"}];
var select="<select id='x'>";
for(var i=0,l=row.length;i<l;i++){
var item=row[i];
select+="<option value='"+item.id+"'>"+item.name+"</option>";
}
select+="</select>";
document.write(select);
By using simple for loop you can read each value and make a select box
var v = { "myJson": [ { "id": 3272, "name": "a" }, { "id": 3255, "name": "b" }, { "id": 3257, "name": "c" }, { "id": 3253, "name": "d" }, { "id": 3256, "name": "e" } ] }
// in your ajax success block write this and v is your response return by ajax
var str ='<select>';
for(var i=0;i<v.myJson.length;i++){
str += '<option value="'+v.myJson[i].id+'">'+v.myJson[i].name+'</option>';
}
str +='</select>';
$("body").html(str)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<body></body>
Here's a working fiddle: https://jsfiddle.net/q1ekcf6z/
var returnData = [{"id":3272,"name":"a"},{"id":3255,"name":"b"},{"id"
:3257,"name":"c"},{"id":3253,"name":"d"
},{"id":3256,"name":"e"}];
var options = '';
returnData.forEach(function(data){
options+= getOption(data.name);
});
var fullDropdown = '<select>' + options + '</select>';
document.write(fullDropdown);
function getOption(textTo){
return '<option>' + textTo + '</option>';
}
I need to convert a large CSV data set to JSON, however the output should be a JSON dictionary like this:
var products = {
"crystal": {
"description": "This is a crystal",
"price": "2.95"
},
"emerald": {
"description": "This is a emerald",
"price": "5.95"
}
};
This is what the CSV table would look like:
I am using a script referenced here to generate the JSON:
var csv = require('csv')
var fs = require('fs')
var f = fs.createReadStream('Fielding.csv')
var w = fs.createWriteStream('out.txt')
w.write('[');
csv()
.from.stream(f, {columns:true})
.transform(function(row, index) {
return (index === 0 ? '' : ',\n') + JSON.stringify(row);
})
.to.stream(w, {columns: true, end: false})
.on('end', function() {
w.write(']');
w.end();
});
However the output from that script is created in this format:
[
{
"name": "crystal",
"description": "This is a crystal",
"price": "2.95"
},
{
"name": "emerald",
"description": "This is a emerald",
"price": "5.95"
}
]
How would I modify the script to get my desired "dictionary" format?
All you need to do is loop over the array and use item.name as key for your dictionary object
var products ={};
data.forEach(function(item){
products[item.name] = item;
});
This will leave the name property in the item but that shouldn't be an issue
I found csv parser library most useful:
var csvText=`status,path,name,ext,checksum,size,document_service_id,document_service_path,message
success,./15-02-2017_17-11/d77c7886-ffe9-40f2-b2fe-e68410d07891//expE1.txt,expE1.txt,txt,38441337865069eabae7754b29bb43e1,414984,8269f7e3-3221-49bb-bb5a-5796cf208fd1,/neuroinftest/20170215/expE1.txt,
success,./15-02-2017_17-11/d77c7886-ffe9-40f2-b2fe-e68410d07891//expE10.txt,expE10.txt,txt,f27e46979035706eb0aaf58c26e09585,368573,2c94ed19-29c9-4660-83cf-c2148c3d6f61,/neuroinftest/20170215/expE10.txt,
success,./15-02-2017_17-11/d77c7886-ffe9-40f2-b2fe-e68410d07891//expE2.txt,expE2.txt,txt,e1040d9546423c823944120de0e5c46c,333308,b3898f5d-1058-4cf3-acf9-76759117b810,/neuroinftest/20170215/expE2.txt,
`
var csv = require('csv');
csv.parse(csvText, {columns: true}, function(err, data){
console.log(JSON.stringify(data, null, 2));
});
In variable csvText I have my comma-separated file, with the first line serving as a header. I use the parse function and I'm passing the {columns: true} to indicated that the first line has the headers. Second parameter in the callback function (data) has the object with keys being the headers and the values being the corresponding csv cells. I use JSON.stringify to print it nicely and the result object looks like this (it puts it into an array):
[
{
"status": "success",
"path": "./15-02-2017_17-11/d77c7886-ffe9-40f2-b2fe-e68410d07891//expE1.txt",
"name": "expE1.txt",
"ext": "txt",
"checksum": "38441337865069eabae7754b29bb43e1",
"size": "414984",
"document_service_id": "8269f7e3-3221-49bb-bb5a-5796cf208fd1",
"document_service_path": "/neuroinftest/20170215/expE1.txt",
"message": ""
},
{
"status": "success",
"path": "./15-02-2017_17-11/d77c7886-ffe9-40f2-b2fe-e68410d07891//expE10.txt",
"name": "expE10.txt",
"ext": "txt",
"checksum": "f27e46979035706eb0aaf58c26e09585",
"size": "368573",
"document_service_id": "2c94ed19-29c9-4660-83cf-c2148c3d6f61",
"document_service_path": "/neuroinftest/20170215/expE10.txt",
"message": ""
},
{
"status": "success",
"path": "./15-02-2017_17-11/d77c7886-ffe9-40f2-b2fe-e68410d07891//expE2.txt",
"name": "expE2.txt",
"ext": "txt",
"checksum": "e1040d9546423c823944120de0e5c46c",
"size": "333308",
"document_service_id": "b3898f5d-1058-4cf3-acf9-76759117b810",
"document_service_path": "/neuroinftest/20170215/expE2.txt",
"message": ""
}
]
UPD: This array can easily be turned into the object you need with reduce:
var res_obj = data.reduce(function(acc, cur, i) {
acc[cur.name] = cur;
return acc;
}, {});
In my case I use the name property as a key. Make sure it's unique.
I think something like this would work :
var products_arr = [{"name":"crystal","description":"This is a crystal","price":"2.95"},
{"name":"emerald","description":"This is a emerald","price":"5.95"}]
var products = {};
for (var i = 0, l = products_arr.length ; i < l ; ++i) {
var x = products_arr[i];
var name = x.name
delete x.name; // deletes name property from JSON object
products[name] = x;
}
This will output :
{
"crystal": {
"description": "This is a crystal",
"price": "2.95"
},
"emerald": {
"description": "This is a emerald",
"price": "5.95"
}
}
If you would like to modify your specific code, you could change the line
return (index === 0 ? '' : ',\n') + JSON.stringify(row);
to
var clonedRow = JSON.parse(JSON.stringify(row));
var key = clonedRow['name'];
delete clonedRow['name'];
var newRow = {};
newRow[key] = clonedRow;
return (index === 0 ? '' : ',\n') + JSON.stringify(newRow);
This creates a new object for each row, modifying the structure according to your requirement.
Your best bet is to use PapaParse, a powerful csv parser/dumper. It supports streams, various string encodings, header row, and it's fast.