I need your help with the json structure !! (I know it's easy but I cann't figure what the error is).
in this code I'm having a json file that contains a list of items (say restaurants) along with some details for each branch, like the address. In my js file I'm trying to print all the addresses that match specific item id.
I will post a sample of the json file and the js code to access it.
here is the json file:
{
"items" :
[
{
"item_id" :"204","details" :[{"country":"usa","city":"NY", "address":"bla bla bla"},{"country":"usa","city":"NY", "address":"another bla bla bla for the same id"}]
},
{
"item_id" :"234","details" :[{"country":"usa","city":"NY", "address":"another bla bla bla"}]
}
]
}
and here is the js code to access that file:
.....
success:function(data){
$.each(data.items, function(i,item){
if (item.item_id == 204 ) {
$("#results").append("<hr/>");
$("#results").append("<span class='result' >" + item.details.address + "</span><br/>");
}
});
}, ....
but it doesn't print any thing.
What do you think?
You don't actually need to use $.each in this case, because you have an array of objects i.e. [{}, {}, {}] is an array of objects, even though you actually have an object of arrays of objects :p. Each object has a specified index i.e. "item" whereas each array of objects has a default index of 0,1,2 etc.
Also yeah, because you have an array of address object details, you need to access them via details[0] or details[1]
Check this example out on jsFiddle
for(var i =0;i<data.items.length;i++) {
if (data.items[i].item_id == "204" ) {
$("#results").append("<hr/>");
$("#results").append("<span class='result' >" + data.items[i].details[0].address + "</span><br/>");
}
}
Your JSON is valid, so that is not the problem.
{
"items": [
{
"item_id": "204",
"details": [
{
"country": "usa",
"city": "NY",
"address": "bla bla bla"
},
{
"country": "usa",
"city": "NY",
"address": "another bla bla bla for the same id"
}
]
},
{
"item_id": "234",
"details": [
{
"country": "usa",
"city": "NY",
"address": "another bla bla bla"
}
]
}
]
}
You can view a modified example at: http://jsfiddle.net/wKDUu/. The code below will loop through the details to accomodate a more dynamic approach.
success:function(data){
var di = data.items;
for(var i=0;i<di.length;i++){
var ii = di[i];
if (ii.item_id == 204 ) {
$("#results").append("<hr/>");
for(var a=0;a<ii.details.length;a++){
$("#results").append("<span class='result' >" + ii.details[a].address + "</span><br/>");
}
}
}
}),
Since item.details is an array, you need to get it via item.details[0].address
Related
I have several objects like this and wonder how I can search between these, say that we got the number 1 and want to figure out what the name is.
Should I loop it or what do you guys suggest?
To make things clear, I do want to get the other objects by using the number. Is it possible?
{
"room": [
{
"number": "1",
"name": "room1"
},
{
"number": "2",
"name": "room2"
}
]
}
You could use a map and use the room number as identifier. This way you can access the room data via the room number like that:
var data = {
"room": [
{
"number": "1",
"name": "room1"
},
{
"number": "2",
"name": "room2"
}
]
};
// or load it from a file:
// var data = require('./data.json');
var rooms = new Map();
for(room of data.room) {
rooms.set(Number(room.number), room);
}
// access data for room with number 1
alert(rooms.get(1).name);
Firstly, bring in the file. Make sure to include the './' before the file name to show that it's from the current directory.
const data = require('./data.json');
Now the JSON data is stored inside the variable data. To access the members, use the dot operator. data.room will return the array of rooms.
To access the individual room, use data.room[i] where i is the numbered element in the array (starting from 0). For example, to access the first room:
const first_room = data.room[0];
This first_room variable can now be used to access the name.
console.log(first_room.name);
This will log "room1" to the console.
You can try this. This will help you.
var roomData = {
"room": [
{
"number": "1",
"name": "room1"
},
{
"number": "2",
"name": "room2"
}
]
}
for(key in roomData.room){
console.log("Room Number - " + roomData.room[key].number);
console.log("Room Name - " + roomData.room[key].name);
}
I have json code that comes out like:
{
"player": [{
"player_id": "1",
"player_name": "Maxfly",
"player_image": "res_573fc05f57c0e.png",
"player_background_image": "images/player_backgrounds/581046687fd89.jpg",
"player_info": "",
"player_region": "North America",
"player_teams": [{
"id": "1",
"team_name": "Test Team",
"team_link": "test-team"
}, {
"id": "65",
"team_name": "Test Team 2",
"team_link": "test-team-2"
}]
}]
}
I've managed to get the player_id and player_name etc. My question is how to I just get the teams? I've tried the following:
$.getJSON("jsonlink",
function(data) {
$.each(data.player.player_teams, function(i,player_team){
var append_data = "<div class='item team_item'><div class='row'><div class='col col_img'><a href='/t/" + player_team.team_name + "' ></a></div></div></div>";
$("#popin-container").append($('<div>' + append_data + '</div>').hide().fadeIn(800));
});
});
Trying to figure out what I'm doing wrong. Is my json object correct?
Thanks!
Your data.player.player_teams is wrong, as data.player is an array, and not an object. You need to loop through it, or in simple way, you need to attach a [0] like this:
$.each(data.player[0].player_teams, function(i, player_team) {
I have a problem and i search for a solution, but i can't find it. I have this Json:
[
{
"name": "Pippo (74)",
"price": "1",
"latitudine": "10.32562",
"longitudine": "44.8003686"
},
{
"name": "pluto",
"price": "2",
"latitudine": "10.32562",
"longitudine": "44.8003686"
}
]
I want retrieve data from the Json (named msg):
num = msg.length;
document.write (num);
document.write (msg[0].name);
But it don't work! Can you help me?
You might use this parse json.
http://api.jquery.com/jquery.parsejson/
var output = jQuery.parseJSON( '[
{
"name": "Pippo (74)",
"price": "1",
"latitudine": "10.32562",
"longitudine": "44.8003686"
},
{
"name": "pluto",
"price": "2",
"latitudine": "10.32562",
"longitudine": "44.8003686"
}]' );
var list = output.data;
$.each(list,function(i,item){
console.log(item.name);
});
you can use var parsedMsg = JSON.parse(msg); to transform to a pure JS object. Then run your script. You also have a typo in 'length'
A shot in the dark here, but guessing your JSON needs to be parsed:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse
var parsedMsg = JSON.parse(msg);
then you can do whatever you like with the data:
num = parsedMsg.length;
console.log(num);
console.log(parsedMsg[0].name);
I want to parse a json file and output in html by using javascript
here is my json file
{"quiz":[
{
"quizName":"Quiz 1",
"question": [
{
"text": "1+1?",
"choiceA": "1",
"choiceB": "2",
}
]
},
{
"quizName":"Quiz 2",
"question": [
{
"text": "2+2?",
"choiceA": "3",
"choiceA": "4",
}
]
}
]}
here is my html
<body>
<div id="placeholder"></div>
<script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script>
$.getJSON('data.json', function(data) {
var output="<ul>";
for (var i in data.quiz) {
output+="<li>" + data.quiz[i].quizName+"</li>";
}
output+="</ul>";
document.getElementById("placeholder").innerHTML=output;
});
</script>
</body>
I want to display all the "quizName" in a list format like this
Quiz 1
Quiz 2
But by code doesn't output anything.
I am new to json and javascript, I don't know whether the json file is not correct or the javascript is not correct. Thanks.
You can't have commas after the last items of an object in a JSON file.
Change:
"choiceB": "2",
To this:
"choiceB": "2"
Do the same for choiceA": "4",
if u r not sure with the Json is right or wrong you can check here online json Parser or jsonEditor
you have extra commas
this is the correct Json
{"quiz":[
{
"quizName":"Quiz 1",
"question": [
{
"text": "1+1?",
"choiceA": "1",
"choiceB": "2"
}
]
},
{
"quizName":"Quiz 2",
"question": [
{
"text": "2+2?",
"choiceA": "3",
"choiceB": "4"
}
]
}
]}
ALso parsing it REFER parsing in fiddle
Hope this Helps
Remove extra commas in your json file at line numbers 9 and 19.
All you need it's do one more loop..
var output="<ul>";
for (var i in dataset) {
for (var j in dataset[i])
{
output+="<li>" + dataset[i][j].quizName+"</li>";
}
}
output+="</ul>";
document.getElementById("placeholder").innerHTML=output;
here you go: http://jsfiddle.net/baximilian/qpJjN/
I have jQuery token input implemented for tagging purposes where a user can search for a tag or create a new one thanks to railscasts ep#382 & ep#258. Data comes from the tags.json url which is the index action of the tags controller. The data from tags.json looks like so:
[
{
"created_at":"2013-06-21T16:30:19Z",
"explanation":"hitting the hosel of the club",
"id":8,
"name":"shank",
"updated_at":"2013-06-21T16:30:19Z",
"updated_by":"andy"
},
{
"created_at":"2013-06-22T17:40:37Z",
"explanation":"hitting the ground before the ball",
"id":12,
"name":"chunk",
"updated_at":"2013-06-22T17:40:37Z",
"updated_by":"andy"
}
]
My tags have a name as well as an explanation so I would like to include them in the results list like the Token and Results Formatting demo here http://loopj.com/jquery-tokeninput/demo.html#formatting.
The code below (number of entries omitted for brevity) is from the jQuery tokenInput Token and Results Formatting demo.
Instead of having "name": "Shank" manually entered here as well as the other omitted entries, how can I extract the name and explanation from tags.json hash and use them in the same was as the results formatter line, e.g. item.name & item.explanation?
tags.js
jQuery(function() {
var question = $('#question_tag_tokens')
return question.tokenInput([{
"name": "Shank",
"explanation": "hitting the hosel of the club"
}
], {
propertyToSearch: ["name"],
resultsFormatter: function(item){ return "<li>" + "<div class='tag' style='display:inline;color:#fff;'>" + item.name + "</div>" + " " + item.explanation + "</li>" },
prePopulate: question.data('preload')
});
});
The source for the example you referred to goes like this:
$(document).ready(function() {
$("#demo-input-local-custom-formatters").tokenInput(
[{
"first_name": "Arthur",
"last_name": "Godfrey",
"email": "arthur_godfrey#nccu.edu",
"url": "https://si0.twimg.com/sticky/default_profile_images/default_profile_2_normal.png"
},
{
"first_name": "Adam",
"last_name": "Johnson",
"email": "wravo#yahoo.com",
"url": "https://si0.twimg.com/sticky/default_profile_images/default_profile_2_normal.png"
},
...
],
{
propertyToSearch: "first_name",
resultsFormatter: function(item){ ... },
tokenFormatter: function(item) { ... }
});
});
tokenInput seems to take an array of objects. Once you load the json with ajax, you just pass it in and tell it what field to search on and some callbacks to format the results.