Json, get info within another level - javascript

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) {

Related

Parse nested JSON Response Javascript

I know there are several threads on this subject but I've looked through over 30 threads without success.
I have managed to parse a JSON response so it looks like this:
{
"1": {
"id": "1",
"name": "Fruit",
.
.
.
"entities": {
"1": {
"id": "1",
"name": "blue bird",
.
.
.
"status": "1"
},
"2": {
using this code
let json = JSON.parse(body);
console.log(json);
Now I want to access the "id", "name" etc. AND the "id" and "name" for the "entities" tag.
So far I have tried:
console.log(json[0]);
console.log(json.id);
which both returns undefined
I have also tried
console.log(json[0].id);
which gives an error
Any ideas?
In this instance, your first key is 1, so you can access it with json[1].
const json = {
"1": {
"id": "1",
"name": "Fruit"
},
"2": {
"id": "2",
"name": "Veggies"
}
};
console.log(json[1]);
In this json, you can reach the id by
json.1.id
But I think that first of all your json is not correctly written, you should have something like
{
"elements": [
{ "id" : 1, "name" : "fruit" },
{ "id" : 2, "name" : "vegetable" }
]
}
like that, json.elements is a collection/array, and you can loop, count, or any other things you will not be able to do because your json looks like a super heavy list of different properties ( he doesn't know that json.1 and json.2 are the same type of objects.
const jsonData = JSON.parse(body);
for (const i in jsonData) {
for (const j in jsonData[i]) {
console.log('${i}: ${jsonData[i][j]}');
}
}

I'd like to push non-existing items inside an already declared object if they don't already exist using lodash in angular

I'm new with lodash but as the title states 'I'd like to push non-existing items inside an already declared object if they don't already exist' that is if I have
var lessdata = {
"id": 1004,
"name": "some event",
"bookmarked": false //not in moredata and I'd like to keep the var as is
};
var moredata = {
"id": 1004,
"name": "some event",
"time": { //from here
"hours": 2,
"minutes": 00,
"currency": "USD"
},
"place": "some place" //to here is new without '"bookmarked": false'
};
I'd like to have my result loaded back into the lessdata variable and have my result look like so
var lessdata = {
"id": 1004,
"name": "some event",
"time": {
"hours": 2,
"minutes": 00,
"currency": "USD"
},
"place": "some place",
"bookmarked": false
};
I stuck knowing know to use lodash apprpriatly in angular and wasnt sure if I need to use angualar's forEach or not.
I've dabbled with two approaches.
version 1
lessdata= _.uniq(lessdata, function(moredata) {
return moredata;
});
version 2
angular.forEach(lessdata, function(lkey, lvalue) {
console.log("[-]lessdata---lkey: " + lkey + ", lvalue: " + lvalue)
angular.forEach(moredata, function(mkey, mvalue) {
console.log("[+]moredata---mkey: " + mkey + ", mvalue: " + mvalue)
lessdata=_.uniq(lessdata, function(moredata) {
return moredata;
});
})
})
$scope.event = lessdata
Im assuming using _.uniq is the best approach? any help would be appreciated and I created a codepen here.
TLDR: just read the title
That's what lodash.defaults does:
Assigns own and inherited enumerable properties of source objects to the destination object for all destination properties that resolve to undefined.
lodash.defaults(lessdata, moredata);

How do I format the display of a select from properties of the objects using angular?

$scope.StateList = {"States": [
{
"Id": 1,
"Code": "AL",
"Name": "Alabama"
},
{
"Id": 2,
"Code": "AK",
"Name": "Alaska"
},
{
"Id": 3,
"Code": "AZ",
"Name": "Arizona"
},
{
"Id": 4,
"Code": "AR",
"Name": "Arkansas"
}]}
And I display the data as follows in an html select:
<select ng-model="Address.State"
ng-options="state.Code as state.Name for state in StateList.States"></select>
Right now this will display the full name of the state in the select like "Arizona". What I would like to do is format the display without adding a new property to the object, to use something like (state.Name, state.Code, state.Id). I am trying to use filters of some sort to do this but I have not figured it out yet. Thanks for your suggestions.
plunker
There are three ways that you can achieve this. The first is to just set the value you want inline:
<select ng-model="Address.State" ng-options="state.Code as (state.Name + ', ' + state.Code + ', ' + state.Id) for state in StateList.States"></select>
Or you can do the same thing, but as a function in your controller:
$scope.display = function(state) {
return state.Name + ', ' + state.Code + ', ' + state.Id;
}
<select ng-model="Address.State" ng-options="state.Code as display(state) for state in StateList.States"></select>
Or you can create a filter (as per PSLs answer)
Try creating a small format filter:-
app.filter('stateName', function() {
return function(itm) {
return [itm.Name , itm.Code, itm.Id].join();
}});
and use it as:-
ng-options="state.Code as (state|stateName) for state in StateList.States
Plnkr

Trouble parsing json with node.js

I wrote a quick script to parse two fairly large json file (~17k records) to do a comparison of the two. I have confirmed they are both valid json (via jsonlintpro) and the same format. (The source is the same so this should be a given. But, I always assume the mistake is mine. And I still do. Just somewhere else.) However, the parsed file just outputs [object, Object]. I'm wondering what the cause could possibly be?
The json format is like this small snippet (anonymized of course):
[
{
"id": "1234",
"name": "Name1",
"url": "https://localhost/Name1",
"date_created": "2013-07-05T18:47:05Z",
"date_cancelled": "",
"props": [
{
"id": "54321",
"type": "Client",
"value": "General Store"
},
{
"id": "65432",
"type": "Contact_Name",
"value": "Joe Smith"
}
]
},
{
"id": "23456",
"name": "Name2",
"url": "https://localhost/Name2",
"date_created": "2014-02-27T17:46:43Z",
"date_cancelled": "",
"props": [
{
"id": "34567",
"type": "Client",
"value": "Bait Shop"
}
]
}]
And here is the pertinent code:
var _ = require('underscore');
var recs = require('./prod.json');
printArr(recs);
console.log(recs.length);
function printArr(arr) {
arr.forEach(function(item) {
console.log(item + ", ");
});
}
Any guidance would be greatly appreciated.
UPDATE:
Ok, so apparently the issue is with my printArr function. I'm not sure what I'm doing wrong there. I'd like to figure it out because I want to expand upon that so I can print selectively.
the parsed file just outputs [object, Object].
This is the expected behavior BECAUSE you are concatenating an object with a string.
Try console.log(item) instead
console.log(item); should indeed print [object, Object], did you try to output its properties instead?
function printArr(arr) {
arr.forEach(function(item) {
console.log( item.id, item.name, item.url, item.date_created, item.date_cancelled, item.props, ';');
});
}
Just export the value from the prod.json file.
prod.json file
module.exports = [
{
"id": "1234",
"name": "Name1"
},
{
"id": "1234",
"name": "Name1"
}]
elsewhere
var recs = require('./prod.json')
console.log(recs)

Facebook looping through returned JSON Open Graph request

Im currently requesting the Open Graph url through JSON like so:
https://graph.facebook.com/me/friends?fields=email,likes,name,birthday,location,website&access_token=$token
My JSON request is succesful, however my issue is to actually loop through the returned data, so that I can list it on my page.
I've tried with the following:
$('#goButton').click(function () {
//Call the JSON feed from the Open Social Graph.
$.getJSON("https://graph.facebook.com/me/friends?fields=email,likes,name,birthday,location,website&access_token=" + savedFbToken + "&callback=?",
//Once it is returned, do something with the JSON:
function (data) {
console.log(data);
//Clear out the placeholder
$('#Placeholder').html("");
//Add some new data
$('#Placeholder').append("<h1>Name:</h1>" + data.name + "");
$('#Placeholder').append("<span>Birthday: "+ data.birthday +"</span><br/>");
$('#Placeholder').append("<span>Location: "+ data.location +"</span><br/>");
$('#Placeholder').append("<span>Id: "+ data.id +"</span><br/><br/>");
});
});
The format returned looks like this:
{
"data": [
{
"name": "Name 1",
"birthday": "10/08/1983",
"location": {
"id": "110343502319180",
"name": "Copenhagen, Denmark"
},
"id": "263901486"
},
{
"name": "Name 2",
"birthday": "02/16/1982",
"location": {
"id": "110398488982884",
"name": "Reykjav\u00edk, Iceland"
},
"id": "502533736"
},
etc...
Any suggestions on how to loop through this correctly?
data actually contains an object with an array of objects also named data, so you would need to loop through that
$('#Placeholder').html("");
for( var i = 0; i < data.data.length; i++ ){
//Add some new data
$('#Placeholder').append("<br />");
$('#Placeholder').append("<h1>Name:</h1>" + data.data[i].name + "");
$('#Placeholder').append("<span>Birthday: "+ data.data[i].birthday +"</span><br/>");
$('#Placeholder').append("<span>Location: "+ data.data[i].location +"</span><br/>");
$('#Placeholder').append("<span>Id: "+ data.data[i].id +"</span><br/><br/>");
}

Categories

Resources