Converting HTML list from json files - javascript

I have a problem with my code when listing countries from json file:
My HTML
<div id="country">country</div>
My JS Code
$.getJSON( "country.js", function( data ) {
var items = [];
$.each( data, function( key, val ) {
items.push( "<li id='" + key + "'>" + val + "</li>" );
});
$( "<ul/>", {
html: items.join( "" )
}).appendTo( "#country" );
});
Fiddle link

You are missing a comma in your json source.
Find this line:
{"countrName" : "Virgin Islands, U.S.", "dialCode" : "+1 340", "countryCode" : "VI"}

Your json source is wrong.
remove var countryList =
Find code: 'TF' and change it to "code": "TF"
You accessed wrong variable.
items.push( "<li id='" + val.countryCode + "'>" + val.countrName + "</li>" );

There was a problem with your generated json, I fixed that one and updated file will be found here
Whats make your file invalid is
For better understanding below is the code that I tested
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<div id="country">country</div>
<script type="text/javascript">
$.getJSON( "country.json", function( data ) {
console.log(data);
var items = [];
$.each( data, function( key, row ) {
items.push( "<li id='" + row.countryCode + "'>" + row.countrName + "</li>" );
});
$( "<ul/>", {
html: items.join( "" )
}).appendTo( "#country" );
});
</script>
N.B: I changed each loop to make it working. Please look into that closely. Also if your country list comes dynamically from any script. Please make that error fixed for generated JSON
Good Luck

Another solution is remove var countryList = from your json file.
use json like a service anyone can use easily.
by writing var countryList this json will limited to javascript only.
Preferred solution is:
read file using $get
like
var items = [];
$.get("https://dl.dropboxusercontent.com/u/100011869/country.js", function(data) {
var gList = eval("(" + contryList + ")");
for (var i = 0; i < gList.length; i++) {
items.push("<li id='" + gList[i].countryCode + "'>" + gList[i].countrName + "</li>");
}
alert(items.join(""));
});

Related

Printing JSON object data to HTML

I am trying to write an html code that shows current version of my software product (something like "v1.0.0") with printing data from a JSON file.
In my server there is a JSON file that stores the my software product version data like below (let's say the location is https://testsite.com/myproductversion.json):
{
"Name": "MyProduct",
"MajorVersion": "1",
"MinorVersion" : "0",
"MaintenanceVersion" : "0"
}
Is it possible? Any help would be appreciated.
fetch('/myproductversion.json').then(res => res.json())
.then(({ MajorVersion, MinorVersion, MaintenanceVersion }) => {
let version = `v${MajorVersion}.${MinorVersion}.${MaintenanceVersion}`;
$('.my-version-goes-here').html(version);
}).catch(console.error);
Just use fetch to make a request for the data.
i hope i understand your question right.
One of many ways is to use jquery/js.
Here is a small snippet to give you an example
$.getJSON( "ajax/test.json", function( data ) {
var items = [];
$.each( data, function( key, val ) {
items.push( "<li id='" + key + "'>" + val + "</li>" );
});
$( "<ul/>", {
"class": "my-new-list",
html: items.join( "" )
}).appendTo( "body" );
});

URL in JSON return as undefined

I'm trying to loop through some JSON but once it gets to the values that are url's, they are returning as undefined. Here's a simplified example of my JS
$.getJSON("https:../houston-locations.js", function(data){
$.each(data, function(i, data){
$("ul.mapList").append(
'<li id="store-' + data.restaurant + '">'+
'<div class="singleLocation">' +
'<button class="directions">DIRECTIONS</button>' +
'Restaurant Details' +
'</div>' +
'</div></li>'
)
})
});
And my JSON:
{ "restaurant":31, "restaurantName":"Shenandoah", "address":"19075 IH 45 S Suite 480", "city":"Shenandoah", "state":"TX", "zip":77385, "phone":"(936) 271-9217", "directions":"https://www.google.com/maps/dir//Pei+Wei,+19075+I-45+%23480,+Shenandoah,+TX+77385/#30.1826863,-95.4533763,17z/", "url":"/texas/31-shenandoah"}
The two keys at the end, "directions" and "url" are the only ones that return as undefined. What am I doing wrong?
Problem is here:
$.getJSON("https:../houston-locations.js", function(data){
$.each(data, function(i, data) {
You are overwriting variable data in function(i, data), consider to change it to value or something else.
Use this code:
$.getJSON( "ajax/ejemplo.json", function( data ) {
var items = [];
$.each( data, function( key, val ) {
items.push( "" + val + "" );
});
$( "", {
"class": "my-new-list",
html: items.join( "" )
}).appendTo( "body" );
});
$.getJSON("https:../houston-locations.js",function(data){
console.log(data);
$.each(data, function( key, value ){
console.log(data.directions);
console.log(data.url);
});
});
the right use of $.getSOn is as above
I found the solution to be something so simple.. It was a cache issue so the new JSON data wasn't being loaded. I did however change the overwriting 'data' values. Thanks everyone!

How to read a local JSON file

I am following a tutorial on YouTube but I couldn't make it run. Basically I have a country.json file.and I am trying to retrieve data inside it. What is wrong here??
This is how country.json file looks like
{
"name": "Germany",
"capital": "Berlin",
"pop": "some value"
}
JavaScript
var container = $("div.container");
$("input#get").click(function () {
$.ajax({
type: "Get",
url: "country.json",
dataType: "json",
successs: function (data) {
$.each(data, function (index, item) {
$.each(item, function (key, value) {
container.append(key + " : " + value + "</br>");
});
container.appendChild("<br/><br>")
});
}
});
});
HTML
<div class="container"></div>
<div id="form-area">
<h2>Get</h2>
<input type="submit" id="get" value="get">
</div>
You can get it like this:-
<head>
<meta charset="UTF-8">
<title>Title</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
</head>
<body>
<div class="container"></div>
<div id="form-area">
<h2>Get</h2>
<input type="submit" id="get" value="get">
</div>
</body>
</html>
<script type="text/javascript">
var container = $(".container"); //check change here
$("#get").click(function () { //check change here
$.getJSON( "country.json", function( data ) {
var myhtml = ''; // create an empty variable
$.each(data, function (key, value) {
myhtml += key + ' : ' + value + '</br>'; // append data to variable
});
container.append( myhtml); // append the whole data (variable) to div
});
});
</script>
Output (on my local browser):- http://prntscr.com/cq2jjt
Note:- to read data from json file $.getJSON() is required.
Check more detail:- http://api.jquery.com/jquery.getjson/
You need https:\\ to run the Ajax, Simply in local file it will not work. Specially in Chrome. Use the Apache server in your machine and add all your file. And run the application through localhost. Ajax call will fire. Before to that, Try the same application in Firefox one. Firefox might do the ajax locally.
we can acheive this by using jquery library..
$.getJSON( "ajax/country.json", function( data ) {
var items = [];
$.each( data, function( key, val ) {
items.push( "<li id='" + key + "'>" + val + "</li>" );
});
$('#form-area').html(items.join(""));
});

Accessing key value pairs from ajax call with jQuery

I am using jquery to call for a Json object from the server. This is my call:
$.getJSON( url, function( data ) {...}
I am getting back (from console.log) the following object:
> 0: Object
cable key: "1"
cable type: "Building Wire..."
> 1: Object
cable key: "2"
cable type: "PVC Wire..."
...
I am trying to access both key and value like the examples below without any luck.
$.getJSON( url, function( data ) {
$.each( data, function( key, value ) {
$( "#CableType" ).append( $( "<option value='" + value['cable key'] + "'>" + value['cable type'] + "</option>" ) );
});
})
Thanks for any help
You are trying to get a property of the VALUE instead of the object. Use
data['cable key']
instead of
value['cable key']
Beside, adding elements to the DOM inside a loop is inefficient. You need to collect your html in a string, and after the loop ends, put it in the DOM. You can do something like this:
$.getJSON( url, function(data){
var htmlCollection = "",
propertyName;
data.forEach(function(pair){
htmlCollection += "<option value='" + pair['cable key'] + "'>" + pair['cable type'] + "</option>";
});
$( "#CableType" ).append(htmlCollection);
});

How to store JSON data from a file into an array of strings

I am working on Dynamic Web Project in Eclipse and using HTML 5 and Javascript as well.
I could manage to parse JSON file that is saved locally in my system though the code below:
$.getJSON( "/Users/Documents/workspace2/sample.json", function( data ) {
var items = [];
$.each( data, function( key, val ) {
items.push( "<li id='" + key + "'>" + val + "</li>" );
});
$( "<ul/>", {
"class": "my-new-list",
html: items.join( "" )
}).appendTo( "body" );
});
Let's suppose this is the JSON file:
{"resource":"A","literals":["B","C","D"]}
My question is: Is there any possibility to have an array of strings to store these elements that are inside the JSON file after parsing. I am quite new to jQuery and couldn't really manage to see these elements stored in an array of strings, for example. Could anyone help me with this issue please.
Try this way :
jsonFile.json
{
"resource":"A",
"literals":["B","C","D"]
}
myFile.html
<html>
<head>
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script type="text/javascript">
$.getJSON( "jsonFile.json", function( data ) {
var items = [];
$.each( data, function( key, val1 ) {
items.push( "<li><a href=#'" + key + "'>" + val1 +"</a></li>");
});
});
$( "<ul/>", {
"class": "my-new-list",
html: items.join( "" )
}).appendTo( "body" );
});
</script>
</head>
<body>
//result will be displayed here
</body>
</html>
Output :
var abc = JSON.stringify({"resource":"A","literals":["B","C","D"]});
var ab = JSON.parse(abc);
var arr=$.map(ab, function(value, index) {
return [value];
});
Hope it helps.

Categories