getJSON() will also parse the JSON for you after fetching, so from then on, you are working with a simple Javascript array ([] marks an array in JSON). The documentation also has examples on how to handle the fetched data.
You can get all the values in an array using a for loop:
$.getJSON("url_with_json_here", function(data){
for (var i = 0, len = data.length; i < len; i++) {
console.log(data[i]);
}
});
Check your console to see the output (Chrome, Firefox/Firebug, IE).
jQuery also provides $.each() for iterations, so you could also do this:
$.getJSON("url_with_json_here", function(data){
$.each(data, function (index, value) {
console.log(value);
});
});
Answer from kapa on Stack OverflowgetJSON() will also parse the JSON for you after fetching, so from then on, you are working with a simple Javascript array ([] marks an array in JSON). The documentation also has examples on how to handle the fetched data.
You can get all the values in an array using a for loop:
$.getJSON("url_with_json_here", function(data){
for (var i = 0, len = data.length; i < len; i++) {
console.log(data[i]);
}
});
Check your console to see the output (Chrome, Firefox/Firebug, IE).
jQuery also provides $.each() for iterations, so you could also do this:
$.getJSON("url_with_json_here", function(data){
$.each(data, function (index, value) {
console.log(value);
});
});
Use the parseJSON method:
var json = '["City1","City2","City3"]';
var arr = $.parseJSON(json);
Then you have an array with the city names.
var data = [{"id":10,"name":"sinu"},{"id":20,"name":"shinto"}];
jQuery(data).each(function(i, item){
$('#output').append(item.id + ' ' + item.name + '<br>');
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="output"></div>
var data = [{"id":10,"name":"sinu"},{"id":20,"name":"shinto"}];
jQuery(data).each(function(i, item){
console.log(item.id, item.name)
})
Use json2.js and parse your array of json object. See the working code below,
var data = '[{"id":10,"name":"sinu"},{"id":20,"name":"shinto"}]';
var obj = JSON.parse(data);
var append= '';
$.each(obj, function(i, $val)
{
append+= $val.id + ',';
});
$('#ids').text(append);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://github.com/douglascrockford/JSON-js/blob/master/json2.js"></script>
<label id='ids'/>
containers contain single node. So simply use
$.each(tainers, function (i, v) {
var tid = v.TID,
top = v.Top,
cat = v.Category,
date = v.Date,
icon = v.Icon,
clink = v.ContainerLink,
uid = v.UniqueID;
cont += '<a href="' + clink + '">' + uid + '</a> ';
$('ul').append('<li>' + tid + ' - ' + top + ' - ' + cat + ' - ' + date + ' - ' + icon + ' - ' + clink + ' - ' + uid + ' (' + cont + ')</li>');
});
The program shows how to read json and store data into textbox:
$(document).ready(function(){
$.getJSON("Test.json",function(data){
$.each(data,function(key,value){
alert(data[key].attrib1name);
alert(data[key].attrib2name);
$('input').val(data[key].enterpriseName);
activities=data[key].activities;
console.log(value);
});
});
});
The following uses Array#reduce to transform the absolute values returned from the server, into the differences between days.
const entries = Object.entries, log = console.log, toJSON = JSON.stringify
const Δ = (arr, prev = 0) =>
arr.reduce((acc, [date, curr]) =>
(acc[date] = curr - prev, prev = curr, acc), {})
const AUTHORITY = 'corona.lmao.ninja'
async function fetchDeltas({ country, days = 30 }) {
const url = `//${AUTHORITY}/v2/historical/${country}?lastdays=${days}`
const { timeline: { cases, deaths, recovered } } = await (await fetch(url)).json()
return {
newCases: Δ(entries(cases)),
newDeaths: Δ(entries(deaths)),
newRecoveries: Δ(entries(recovered))
}
}
fetchDeltas({ country: 'mauritius' }).then(log)
(async function() {
const {cases, deaths} = (await (await
fetch("https://corona.lmao.ninja/v2/historical/mauritius?lastdays=30")).json()).timeline;
console.log("Cases", diffEvents(cases));
console.log("Deaths", diffEvents(deaths));
})();
const diffEvents = (value) => {
const dates = Object.keys(value);
return dates.map((date, index) => {
const currentDate = date;
const prevDate = dates[index-1];
return {
date: currentDate,
count: index>0 ? value[date] - value[dates[index-1]] : value[date]
};
});
};
Ignoring the calls to your local storage, i have made a simplified example you can use as guide:
// Create the JSON object and stringify
var item1 = {
item_id:332443,
item_rank:3.6,
item_type:["BMW","Camry","Ford"]
};
var item2 = {
item_id:354443,
item_rank:2.6,
item_type:["BMW","Camry","Ford","Tesla","GM","Chevrolet"]
};
var itemsRecords = {
items:[item1,item2]
};
var itemsRecordsJSON = JSON.stringify(itemsRecords);
// On document ready, parse the JSON string to object again
// and show their items on the console.
$(document).ready(function()
{
var records = JSON.parse(itemsRecordsJSON);
records.items.forEach(function(item)
{
//console.log(item);
$("#results").append(
"<b>Id=" + item.item_id +
" - Rank=" + item.item_rank +
" - Type=" + item.item_type.join(",") +
"</b><hr>"
);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="results">
</div>
Run code snippetEdit code snippet Hide Results Copy to answer Expand
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>WDV321 Advanced Javascript - JSON</title>
<script
src="https://code.jquery.com/jquery-3.3.1.slim.min.js"
integrity="sha256-3edrmyuQ0w65f8gfBsqowzjJe2iM6n0nKciPUp8y+7E="
crossorigin="anonymous"></script>
<script src="createJSONArray.js"></script>
<script>
$(document).ready(function(){
// get the objects from local storage
allRecords = localStorage.getItem("studentRecords");
// convert JSON Object to Javascript object
var records = JSON.parse(allRecords);
// add counter
i =0;
// add loop to read the objects
records.students.forEach(function(item)
{
var listAdd = "";
// create variable to exract the array
var courses = records.students[i].student_courses;
// add inner counter
var j=0;
$.each( courses, function( ){
listAdd = listAdd + "<li style = 'margin-left: 80px'>" + courses[j] + "</li>" ;
j++;
courses.join("<br/>")
});
$("body").append ("<div class='studentCard'>" + "<h3>Student ID:<span id='id'>" + records.students[i].student_id + "</span></h3>" + "<p>Student GPA:<span id='gpa'>"+ records.students[i].student_gpa +"</span></p>" + "<p>Student Courses: </p>" + "<ul id = 'classes'></ul>" + listAdd + "</p>" + "</div>" );
i++;
});
});
</script>
<style>
.studentCard {
width:200px;
box-sizing:border-box;
background-color:lightblue;
padding-left:5px;
padding-top:3px;
border:thin solid blue;
box-shadow: 2px 2px 2px grey;
margin: 5px;
}
.studentCard h3 {
margin:0px;
}
# sort {
margin-left: 10px;
}
</style>
</head>
<body>
<h3>Creating and consuming a JSON object</h3>
</html>
How about:
var dates = new Array();
var prices = new Array();
for (foo in data) {
dates.push(data[foo].poll_date);
prices.push(data[foo].prix);
}
jsFiddle example. Plus it uses plain JavaScript.
you should be able to do something like :
$.getJSON(url, null, function(data) {
$.each(data, function(i,item){
dates.push(item.poll_date);
prices.push(parseFloat(item.prix));
$("#testout").append("A:" + item.poll_date + " B:" + item.prix + "<br>");
});
});
You should grab the "client" property first which is an array. Once you grab it, then you can iterate over it as an array.
{ //object | obj
"client":[ //property (array) | obj.client
{ //object inside array | obj.client[0]
"ClientID":"0000000001",
"Name":"Valdez Gilberto JR", //property | obj.client[0].Name
"Phone":"(956)542-8148",
"MedActID":"10",
"Gender":"M",
"Division":"WP",
"Address":"1905 Illinois Ave N",
"Class":"",
"CityState":"Brownsville TX 78521-6732"
},
{
"ClientID":"0000000002",
"Name":"Salazar Olga F",
"Phone":"(956)546-3909",
"MedActID":"100",
"Gender":"F",
"Division":"MP",
"Address":"Route 8 Box 626 (San Pedro)",
"Class":"",
"CityState":"Brownsville TX 78520"
}
]
}
This code will iterate over the objects inside the "client" property, and alert the names.
var obj = JSON.parse(data);
var client = obj.client; //client prop is an array
for(var i = 0; i < client.length; i++){
alert(client[i].Name);
}
You are trying to iterate an object, but you can't do that. What you want is to iterate trough the array which is in your object, keyed by client
Try this:
for(var i = 0; i < obj.client.length; i++){
console.log(obj.client[i].Name)
}
No, with eval is not safe, you can use JSON parser that is much safer: var myObject = JSON.parse(data);
For this use the lib https://github.com/douglascrockford/JSON-js
I know this is pretty long after your post, but wanted to post for others who might be experiencing this issue and stumble across this post as I did.
It seems there's something about jquery's $.each that changes the nature of the elements in the array.
I wanted to do the following:
$.getJSON('/ajax/get_messages.php', function(data) {
/* data:
[{"title":"Failure","details":"Unsuccessful. Please try again.","type":"error"},
{"title":"Information Message","details":"A basic informational message - Please be aware","type":"info"}]
*/
console.log ("Data0Title: " + data[0].title);
// prints "Data0Title: Failure"
console.log ("Data0Type: " + data[0].type);
// prints "Data0Type: error"
console.log ("Data0Details: " + data[0].details);
// prints "Data0Details: Unsuccessful. Please try again"
/* Loop through data array and print messages to console */
});
To accomplish the loop, I first tried using a jquery $.each to loop through the data array. However, as the OP notes, this doesn't work right:
$.each(data, function(nextMsg) {
console.log (nextMsg.title + " (" + nextMsg.type + "): " + nextMsg.details);
// prints
// "undefined (undefined): undefined
// "undefined (undefined): undefined
});
This didn't exactly make sense since I am able to access the data[0] elements when using a numeric key on the data array. So since using a numerical index worked, I tried (successfully) replacing the $.each block with a for loop:
var i=0;
for (i=0;i<data.length;i++){
console.log (data[i].title + " (" + data[i].type + "): " + data[i].details);
// prints
// "Failure (error): Unsuccessful. Please try again"
// "Information Message (info): A basic informational message - Please be aware"
}
So I don't know the underlying problem, a basic, old fashioned javascript for loop seems to be a functional alternative to jquery's $.each
This works perfectly
function myFunction(dataFromServer){
var parsedJSON = JSON.parse(dataFromServer.d);
for (var i=0;i<parsedJSON.length;i++) {
alert(parsedJSON[i].Id);
}
}
But this doens't
function myFunction(dataFromServer){
var parsedJSON = JSON.parse(dataFromServer.d);
for (var item in parsedJSON) {
alert(item.Id);
}
}
You can just access them as you would any object:
var id = item.Id;
if (item.IsGood) { ... }
If you wish to enumerate them to use somehow, have a look at this SO question.