Accessing key value pairs from ajax call with jQuery - javascript

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);
});

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!

javascript multidimensional array acting strangely

I am trying to setup a jquery autocomplete input based on the user's input in a previous field.
I have a php script that returns a json variable to this jquery post function. however I can't seem to set up my array correctly after.
I have tried just setting a variable to the data and processing the array outside of the $.post function, but still no luck.
I am just unsure how and why the sub-value of my array is alerted correctly when the "parent" value as such is shown as null?
function populateMetrics(light_id){
var availableMetrics = [];
$.post(
"getLightMetrics.php",
{
light_id: light_id,
},
function(data) {
$.each(data, function(index, item){
alert(index); //correct index
availableMetrics[index] = [];
availableMetrics[index]['value'] = item.benchmark_id;
alert(availableMetrics[index]['value']); //correct value
alert(availableMetrics[index]); //null?
availableMetrics[index]['label'] = item.benchmark_variant + "-" + item.benchmark_metric;
alert(availableMetrics[index]['label']); //correct
alert(item.benchmark_id + " = " + item.benchmark_variant + "-" + item.benchmark_metric);
alert(availableMetrics[index]); //still null
});
alert(availableMetrics); //all null, but correct amount
$( "#metric" ).autocomplete({
source: availableMetrics,
focus: function( event, ui ) {
$( "#metric" ).val( ui.item.label );
return false;
},
select: function( event, ui ) {
$( "#metric" ).val( ui.item.label );
$( "#metric_id" ).val( ui.item.value );
return false;
}
});
},
"json"
);
}
Multi-dimensional arrays in JavaScript can only have integer-based indexes. They don't work like Associate Arrays do in PHP.
The code you're looking for is probably
var availableMetrics = [];
$.each(data, function(index, item) {
availableMetrics[index] = {
value: item.benchmark_id,
label: item.benchmark_variant + "-" + item.benchmark_metric
};
});
This will create an array of objects that have value and label properties. You would then be able to retrieve the values from your array using either of these notations:
availableMetrics[index]['value'];
availableMetrics[index].value;

Converting HTML list from json files

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(""));
});

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