Adding extra values in json object - javascript

For Example
I have Object named tempobj and below are tempobj[0] and tempobj[1] sample data.
I want to add extra info like name and status this object
tempobj ["info"]["name"] = "title";
tempobj ["info"]["id"] = "23243";
But when i do stringify , Jquery is ignoring this value...how can i add data like this to this kind of structure.
[
[{
"name": "Breakfast",
"value": "buffalo strip ",
"check": 0
}, {
"name": "snack ",
"value": "pecan pie butter",
"check": 0
}, {
"name": "dessert",
"value": "chocolate zucchani brownie",
"check": 0
}],
[{
"name": "Breakfast",
"value": "Stir Fried Kale and Baccon ",
"check": 1
}, {
"name": "snack ",
"value": "Smoked Salmon nori roll "
}, {
"name": "dessert",
"value": "Apple muffins"
}]

tempobj is an array ([]).
When you try to set some values with:
tempobj["info"]["name"] = "title";
tempobj["info"]["id"] = "23243";
you treat it like an object ({}).
If you want to add some data to your tempobj, you have to change its structure like this for example:
{
"info": {
"name": "title",
"id": "23243"
},
"items": [
[{
"name": "Breakfast",
"value": "buffalo strip ",
"check": 0
}, {
"name": "snack ",
"value": "pecan pie butter",
"check": 0
}, {
"name": "dessert",
"value": "chocolate zucchani brownie",
"check": 0
}],
[{
"name": "Breakfast",
"value": "Stir Fried Kale and Baccon ",
"check": 1
}, {
"name": "snack ",
"value": "Smoked Salmon nori roll "
}, {
"name": "dessert",
"value": "Apple muffins"
}]
]
}
Here is a sample:
var tempobj = {
items: [
[{
"name": "Breakfast",
"value": "buffalo strip ",
"check": 0
}, {
"name": "snack ",
"value": "pecan pie butter",
"check": 0
}, {
"name": "dessert",
"value": "chocolate zucchani brownie",
"check": 0
}],
[{
"name": "Breakfast",
"value": "Stir Fried Kale and Baccon ",
"check": 1
}, {
"name": "snack ",
"value": "Smoked Salmon nori roll "
}, {
"name": "dessert",
"value": "Apple muffins"
}]
]
}
tempobj.info = {
name: 'title',
id: '23243'
};
// Another way:
//tempobj.info = {};
//tempobj.info.name = 'title';
//tempobj.info.id = '23243';
console.log(JSON.stringify(tempobj));

It sounds like you're doing something like this:
// Create an array
var a = [];
// Add an entry to it
a[0] = "I'm an array entry";
// Add a non-entry property to it
a.foo = "bar";
// Convert to JSON
var json = JSON.stringify(a);
...and finding that the string doesn't have the foo property.
That's correct. JSON's arrays don't support arbitrary non-entry properties the way JavaScript's arrays do, and so they get silently dropped during serialization (the same way properties with the value undefined or referring to functions do).
The answer is not to do that if you need to go through JSON.
But, the structure you quoted later in your question doesn't do that, and can readily be created like this:
var data = [
[
{
"name": "Breakfast",
"value": "buffalo strip ",
"check": 0
},
{
"name": "snack ",
"value": "pecan pie butter",
"check": 0
},
{
"name": "dessert",
"value": "chocolate zucchani brownie",
"check": 0
}
],
[
{
"name": "Breakfast",
"value": "Stir Fried Kale and Baccon ",
"check": 1
},
{
"name": "snack ",
"value": "Smoked Salmon nori roll "
},
{
"name": "dessert",
"value": "Apple muffins"
}
]
];
var json = JSON.stringify(data);
That structure is (from the outside in): An array containing two entries, each of which is another array; within each array, you have a series of objects, which have properties.
I don't know why you want to have the two arrays inside the outermost array, but that's what the structure showed.
If you meant just a single array, that would look like this if you were creating it all at once:
var data = [
{
"name": "Breakfast",
"value": "buffalo strip ",
"check": 0
},
{
"name": "snack ",
"value": "pecan pie butter",
"check": 0
},
{
"name": "dessert",
"value": "chocolate zucchani brownie",
"check": 0
},
{
"name": "Breakfast",
"value": "Stir Fried Kale and Baccon ",
"check": 1
},
{
"name": "snack ",
"value": "Smoked Salmon nori roll "
},
{
"name": "dessert",
"value": "Apple muffins"
}
];
var json = JSON.stringify(data);
...or if building it up over time:
var data = [];
data.push({
name: "Breakfast",
value: "buffalo strip ",
check: 0
});
data.push({
name: "snack ",
value: "pecan pie butter",
check: 0
});
// ...
var json = JSON.stringify(data);

Related

Swimlane ngx-charts in Angular2 - Different styles on a single line chart

I have a single line chart, with dates on the X axis. After a certain date,
I would like the line to be a different color. Is this possible using ngx-charts?
Let us assume the date after which you want to change the color as T.
Now you can divide the series into 2 parts
The from start date to T
From T to end date.
And now you can plot the graph using different color for different series
The following data will generate the desired graph.
var data = [
{
"name": "Current",
"series": [
{
"value": 5599,
"name": "2016-09-20T01:04:28.176Z"
},
{
"value": 6247,
"name": "2016-09-20T12:51:24.713Z"
},
{
"value": 4283,
"name": "2016-09-18T15:42:04.800Z"
},
{
"value": 2643,
"name": "2016-09-13T20:10:53.904Z"
},
{
"value": 4105,
"name": "2016-09-18T06:15:10.845Z"
},
{
"name": "2016-09-18T13:08:42.085Z",
"value": 4401
},
{
"name": "2016-09-20T01:04:28.176Z",
"value": 3443
}
]
},
{
"name": "Future",
"series": [
{
"value": 3443,
"name": "2016-09-20T01:04:28.176Z"
},
{
"value": 2604,
"name": "2016-09-20T12:51:24.713Z"
},
{
"value": 2158,
"name": "2016-09-18T15:42:04.800Z"
},
{
"value": 5519,
"name": "2016-09-13T20:10:53.904Z"
},
{
"value": 4532,
"name": "2016-09-18T06:15:10.845Z"
},
{
"name": "2016-09-18T13:08:42.085Z",
"value": 2474
}
]
}
]

How to access all the matches inside matches array

{
"name": "English Premier League 2015/16",
"rounds": [
{
"name": "Play-Off um 1 Premierleague-Platz:",
"matches": [
{
"date": "2015-08-08",
"team1": {
"key": "manutd",
"name": "Manchester United",
"code": "MUN"
},
"team2": {
"key": "tottenham",
"name": "Tottenham Hotspur",
"code": "TOT"
},
"score1": 1,
"score2": 0
},
{
"date": "2015-08-08",
"team1": {
"key": "bournemouth",
"name": "Bournemouth",
"code": "BOU"
},
"team2": {
"key": "astonvilla",
"name": "Aston Villa",
"code": "AVL"
},
"score1": 0,
"score2": 1
},
{
"date": "2015-08-08",
"team1": {
"key": "everton",
"name": "Everton",
"code": "EVE"
},
"team2": {
"key": "watford",
"name": "Watford",
"code": "WAT"
},
"score1": 2,
"score2": 2
},
{
"date": "2015-08-08",
"team1": {
"key": "leicester",
"name": "Leicester City",
"code": "LEI"
},
"team2": {
"key": "sunderland",
"name": "Sunderland",
"code": "SUN"
},
"score1": 4,
"score2": 2
},
{
"date": "2015-08-08",
"team1": {
"key": "norwich",
"name": "Norwich",
"code": "NOR"
},
"team2": {
"key": "crystalpalace",
"name": "Crystal Palace",
"code": "CRY"
},
"score1": 1,
"score2": 3
},
{
"date": "2015-08-08",
"team1": {
"key": "chelsea",
"name": "Chelsea",
"code": "CHE"
},
"team2": {
"key": "swansea",
"name": "Swansea",
"code": "SWA"
},
"score1": 2,
"score2": 2
},
{
"date": "2015-08-09",
"team1": {
"key": "arsenal",
"name": "Arsenal",
"code": "ARS"
},
"team2": {
"key": "westham",
"name": "West Ham United",
"code": "WHU"
},
"score1": 0,
"score2": 2
},
{
"date": "2015-08-09",
"team1": {
"key": "newcastle",
"name": "Newcastle United",
"code": "NEW"
},
"team2": {
"key": "southampton",
"name": "Southampton",
"code": "SOU"
},
"score1": 2,
"score2": 2
},
{
"date": "2015-08-09",
"team1": {
"key": "stoke",
"name": "Stoke City",
"code": "STK"
},
"team2": {
"key": "liverpool",
"name": "Liverpool",
"code": "LIV"
},
"score1": 0,
"score2": 1
},
{
"date": "2015-08-10",
"team1": {
"key": "westbrom",
"name": "West Bromwich Albion",
"code": "WBA"
},
"team2": {
"key": "mancity",
"name": "Manchester City",
"code": "MCI"
},
"score1": 0,
"score2": 3
}
]
}
]
}
I want to log all the matches which are inside matches array . But i can't seem to access them because there are objects ,arrays ,more arrays and more objects nested inside one another. Kinda confused.please help explaining how to access elements in such situation. Which loops to use, what to do in case of looping through objects and so on. Hope I have explained my problem quite elaborately.
You can try this this code here:
const data = {"name":"English Premier League 2015/16","rounds":[{"name":"Play-Off um 1 Premierleague-Platz:","matches":[{"date":"2015-08-08","team1":{"key":"manutd","name":"Manchester United","code":"MUN"},"team2":{"key":"tottenham","name":"Tottenham Hotspur","code":"TOT"},"score1":1,"score2":0},{"date":"2015-08-08","team1":{"key":"bournemouth","name":"Bournemouth","code":"BOU"},"team2":{"key":"astonvilla","name":"Aston Villa","code":"AVL"},"score1":0,"score2":1},{"date":"2015-08-08","team1":{"key":"everton","name":"Everton","code":"EVE"},"team2":{"key":"watford","name":"Watford","code":"WAT"},"score1":2,"score2":2},{"date":"2015-08-08","team1":{"key":"leicester","name":"Leicester City","code":"LEI"},"team2":{"key":"sunderland","name":"Sunderland","code":"SUN"},"score1":4,"score2":2},{"date":"2015-08-08","team1":{"key":"norwich","name":"Norwich","code":"NOR"},"team2":{"key":"crystalpalace","name":"Crystal Palace","code":"CRY"},"score1":1,"score2":3},{"date":"2015-08-08","team1":{"key":"chelsea","name":"Chelsea","code":"CHE"},"team2":{"key":"swansea","name":"Swansea","code":"SWA"},"score1":2,"score2":2},{"date":"2015-08-09","team1":{"key":"arsenal","name":"Arsenal","code":"ARS"},"team2":{"key":"westham","name":"West Ham United","code":"WHU"},"score1":0,"score2":2},{"date":"2015-08-09","team1":{"key":"newcastle","name":"Newcastle United","code":"NEW"},"team2":{"key":"southampton","name":"Southampton","code":"SOU"},"score1":2,"score2":2},{"date":"2015-08-09","team1":{"key":"stoke","name":"Stoke City","code":"STK"},"team2":{"key":"liverpool","name":"Liverpool","code":"LIV"},"score1":0,"score2":1},{"date":"2015-08-10","team1":{"key":"westbrom","name":"West Bromwich Albion","code":"WBA"},"team2":{"key":"mancity","name":"Manchester City","code":"MCI"},"score1":0,"score2":3}]}]};
data.rounds.forEach((round) => {
round.matches.forEach((match) => {
console.log(`Results ${ match.score1 } | ${ match.score2 }`);
})
});
Basically you're using a mixture of array and object references.
You use your object references (data.rounds or round.matches) to get to specific properties on your object. Then you can you array functions (.forEach() which you can read about here) to access the objects in each array. Then you just access the properties of those sub objects.
Hope this helps.
Building on Phil's comment, something like this should help you iterate through the matches and do something with each.
obj.rounds[0].matches.forEach(match => {
console.log(match);
})
The snippet shared is actually a object. Inside this object there is a key by name rounds, which is again array of objects.
So data.rounds will give the value which is an array.
Inside this array there is array of matches. But data.rounds is array of only one object. Hence data.rounds[0] will allow to access it's value. [0] being the index, since in array the first element is at 0 index & data.rounds[0].matches will give the array of matches
var data = {
"name": "English Premier League 2015/16",
"rounds": [{
"name": "Play-Off um 1 Premierleague-Platz:",
"matches": [
//other objects
]
}
console.log(data.rounds[0].matches)
DEMO
I guest that your data is structured in a JSON that you are going to decoded using the json_decode function like this:
$myMatches = json_decode($yourJSON);
After that JSON gets converted into an object you can access any property by following the following rules:
Every opening curly bracket on the JSON gets converted into an object, and you will have to use the arrow syntax like this: $myMatches->attribute
For example, imagine an object "$person" with the following structure:
{
"name": "manutd",
"lastname": "Manchester United",
"phone": "MUN"
}
To print the name you will have to do:
echo $person->name;
On the other hand, every normal bracket gets transformed into an array and you have to use brackets to access that information (like any other array), like this: $myMatches['attribute']
For example that same person but now with array syntax:
[
"name": "manutd",
"lastname": "Manchester United",
"phone": "MUN"
]
To print the name you will have to do:
echo $person['name'];
Now, for your question in particular
That said, if you want to print the date of the first round of the first match, you will have to do:
echo $myMatches->rounds[0]->matches[0]->date;
I have prepared this functions for your disposal:
//This function returns all the matches in one tournament round
function getMatchesOfRound($myMatches, $roundNumber)
{
return $myMatches->rounds[$roundNumber]->matches;
}
//This function returns all the matches played by $teamKey
function getAllMatchesOfTeam($myMatches, $teamKey){
$matches = [];
foreach($myMatches->rounds as $rounds)
foreach($rounds->matches as $match)
if($match->team1->key == $teamKey || $match->team2->key == $teamKey) $matches[] = $match;
return $matches;
}
//this function determines the winner of a given match and returns the $teamKey
function getWinerFromMatch($match){
if($match->score1 > $match->score2) return $match->team1;
else if($match->score1 < $match->score2) return $match->team2;
else return null;
}
//This function returns all matches won by $teamKey
function getAllMatchesOfTeam($myMatches, $teamKey){
$matches = [];
foreach($myMatches->rounds as $rounds)
foreach($rounds->matches as $match)
if(getWinerFromMatch($match) == $teamKey) $matches[] = $match;
return $matches;
}
//This function returns all ties
function getAllMatchesOfTeam($myMatches, $teamKey){
$matches = [];
foreach($myMatches->rounds as $rounds)
foreach($rounds->matches as $match)
if(getWinerFromMatch($match) == null) $matches[] = $match;
return $matches;
}
You get the idea, I hope this helps. I have not tested the code, maybe it has minor sytax errors.
result = {
"name": "English Premier League 2015/16",
"rounds": [
{
"name": "Play-Off um 1 Premierleague-Platz:",
"matches": [
{
"date": "2015-08-08",
"team1": {
"key": "manutd",
"name": "Manchester United",
"code": "MUN"
},
"team2": {
"key": "tottenham",
"name": "Tottenham Hotspur",
"code": "TOT"
},
"score1": 1,
"score2": 0
},
{
"date": "2015-08-08",
"team1": {
"key": "bournemouth",
"name": "Bournemouth",
"code": "BOU"
},
"team2": {
"key": "astonvilla",
"name": "Aston Villa",
"code": "AVL"
},
"score1": 0,
"score2": 1
},
{
"date": "2015-08-08",
"team1": {
"key": "everton",
"name": "Everton",
"code": "EVE"
},
"team2": {
"key": "watford",
"name": "Watford",
"code": "WAT"
},
"score1": 2,
"score2": 2
},
{
"date": "2015-08-08",
"team1": {
"key": "leicester",
"name": "Leicester City",
"code": "LEI"
},
"team2": {
"key": "sunderland",
"name": "Sunderland",
"code": "SUN"
},
"score1": 4,
"score2": 2
},
{
"date": "2015-08-08",
"team1": {
"key": "norwich",
"name": "Norwich",
"code": "NOR"
},
"team2": {
"key": "crystalpalace",
"name": "Crystal Palace",
"code": "CRY"
},
"score1": 1,
"score2": 3
},
{
"date": "2015-08-08",
"team1": {
"key": "chelsea",
"name": "Chelsea",
"code": "CHE"
},
"team2": {
"key": "swansea",
"name": "Swansea",
"code": "SWA"
},
"score1": 2,
"score2": 2
},
{
"date": "2015-08-09",
"team1": {
"key": "arsenal",
"name": "Arsenal",
"code": "ARS"
},
"team2": {
"key": "westham",
"name": "West Ham United",
"code": "WHU"
},
"score1": 0,
"score2": 2
},
{
"date": "2015-08-09",
"team1": {
"key": "newcastle",
"name": "Newcastle United",
"code": "NEW"
},
"team2": {
"key": "southampton",
"name": "Southampton",
"code": "SOU"
},
"score1": 2,
"score2": 2
},
{
"date": "2015-08-09",
"team1": {
"key": "stoke",
"name": "Stoke City",
"code": "STK"
},
"team2": {
"key": "liverpool",
"name": "Liverpool",
"code": "LIV"
},
"score1": 0,
"score2": 1
},
{
"date": "2015-08-10",
"team1": {
"key": "westbrom",
"name": "West Bromwich Albion",
"code": "WBA"
},
"team2": {
"key": "mancity",
"name": "Manchester City",
"code": "MCI"
},
"score1": 0,
"score2": 3
}
]
}
]
};
for ( let i=0, totalRounds = result.rounds.length; i < totalRounds; i++) {
let round = result.rounds[i];
console.log( round.name );
for ( let j=0, totalMatches = round.matches.length; j < totalMatches; j++ ) {
let match = round.matches[j];
console.log( match.date + ': ' + match.team1.name + " " + match.score1 + " - " + match.team2.name + " " + match.score2)
}
}
You can fetch all the matches in a variable then iterate over it using any loop.
If there is only 1 round then this will do the task.
var matches = object.rounds[0]. matches;
for(var match in matches){
console.log(match);
}
If there more rounds then you to first iterate over rounds and inside that loop fetch all the matches in that particular round.
for(var round in object.rounds){
var matches = round.matches;
for(var prop in matches){
console.log(prop);
}
}

Functional approach to transform an array of objects into a hierarchical structure with aggregates

I'm looking for a functional solution to map this object into a hierarchical structure and group by practice, subjectarea, and asset so that this object:
var data = {
"research": [
{ "practice": "Talent Management", "id": "20992", "title": "Creating a Culture of Leadership", "subjectArea": "Talent Strategy" },
{ "practice": "Talent Management", "id": "20993", "title": "Talent Economics", "subjectArea": "Talent Strategy" },
{ "practice": "Talent Management", "id": "20990", "title": "Finding the Right Talent", "subjectArea": "Recruiting" },
{ "practice": "Human Resources", "id": "20994", "title": "Tips from the Front", "subjectArea": "HR Training" },
{ "practice": "Human Resources", "id": "20995", "title": "Reward Programs", "subjectArea": "Employee Engagement" },
]
}
gets transformed into this (count the number of items for a practice and add the subject areas for the practice as children, count the number of items for a subject area within the practice and add the asset (id and title) as children for the subject area):
{
"name": "research",
"children": [
{
"name": "Talent Management", "size": 3, "children": [
{
"name": "Talent Strategy", "size": 2, "children": [
{ "name": "Creating a Culture of Leadership", "id": "20992", "size": 1 },
{ "name": "Talent Economics", "id": "20993", "size": 1 }
]
},
{
"name": "Recruiting", "size": 1, "children": [
{ "title": "Finding the Right Talent", "id": "20990", "size": 1 },
]
}
]
},
{
"name": "Human Resources", "size": 2, "children": [
{
"name": "HR Training", "size": 1, "children": [
{ "name": "Tips from the Front", "id": "20994", "size": 1 },
]
},
{
"name": "Employee Engagement", "size": 1, "children": [
{ "name": "Reward Programs", "id": "20995", "size": 1 },
]
}
]
},
]
}
I haven't been able to sort out the map and reduce combination to use to yield the correct result with counts, and appreciate any insight.
It might not be what SO is for (as per comments above), but in case anyone needs to transform an array of flat objects into a hierarchical structure that you can simply specify the nesting order, number of levels, and field names, here is a recursive function to do so - https://github.com/lance-p/configurable-transform-flat-array-to-nested. Hope it might be of help to others.

Getting a value from JSON, Node.js

I am having trouble with getting a value from inside of a JSON file, which has been retrieved from the Steam API (http://steamcommunity.com/dev).
The problem occurs when I attempt to print the data, the Node.js file code is below:
var data = JSON.parse(body); // Stores the JSON data which has been retrieved
console.log(data.result.toString(350462890).market_hash_name); // Attempts to grab the value of the market_hash_name from the JSON data and display it to screen
I get the following response: "undefined".
JSON data used below:
{
"result": {
"350462890": {
"icon_url": "fWFc82js0fmoRAP-qOIPu5THSWqfSmTELLqcUywGkijVjZYMUrsm1j-9xgEObwgfEh_nvjlWhNzZCveCDfIBj98xqodQ2CZknz5-OOqhNQh0fTvSAK5KVPAoywXpDS4n5YliBtazruNQfgrssNfPN-IqYtkdSpTZU_OCYAir70luiaAPfZOIqHznw223bZvDH3kW",
"icon_url_large": "fWFc82js0fmoRAP-qOIPu5THSWqfSmTELLqcUywGkijVjZYMUrsm1j-9xgEObwgfEh_nvjlWhNzZCveCDfIBj98xqodQ2CZknz5-OOqhNQh0fTvSAK5KVPAoywXpDS4n5fhvVcWx8vUHe126vYrANLYvNI1FG5LWCPfXM1304048hqALKpffqSu9jyvoMjgCRVO1rexMsCC1",
"icon_drag_url": "",
"name": "Dual Berettas | Panther",
"market_hash_name": "Dual Berettas | Panther (Field-Tested)",
"market_name": "Dual Berettas | Panther (Field-Tested)",
"name_color": "D2D2D2",
"background_color": "",
"type": "Mil-Spec Grade Pistol",
"tradable": "1",
"marketable": "1",
"commodity": "0",
"fraudwarnings": "",
"descriptions": {
"0": {
"type": "html",
"value": "Exterior: Field-Tested",
"app_data": ""
},
"1": {
"type": "html",
"value": " ",
"app_data": ""
},
"2": {
"type": "html",
"value": "Firing two large-mag Berettas at once will lower accuracy and increase load times. On the bright side, you'll get to fire two large-mag Berettas at once. It has been painted in a black, grey and red color scheme.",
"app_data": ""
},
"3": {
"type": "html",
"value": " ",
"app_data": ""
},
"4": {
"type": "html",
"value": "The Arms Deal 3 Collection",
"color": "9da1a9",
"app_data": {
"def_index": "65535",
"is_itemset_name": "1"
}
},
"5": {
"type": "html",
"value": " ",
"app_data": ""
}
},
"owner_descriptions": "",
"actions": {
"0": {
"name": "Inspect in Game...",
"link": "steam://rungame/730/76561202255233023/+csgo_econ_action_preview%20S%owner_steamid%A%assetid%D14429613083935122456"
}
},
"market_actions": {
"0": {
"name": "Inspect in Game...",
"link": "steam://rungame/730/76561202255233023/+csgo_econ_action_preview%20M%listingid%A%assetid%D14429613083935122456"
}
},
"tags": {
"0": {
"internal_name": "CSGO_Type_Pistol",
"name": "Pistol",
"category": "Type",
"category_name": "Type"
},
"1": {
"internal_name": "weapon_elite",
"name": "Dual Berettas",
"category": "Weapon",
"category_name": "Weapon"
},
"2": {
"internal_name": "set_weapons_iii",
"name": "The Arms Deal 3 Collection",
"category": "ItemSet",
"category_name": "Collection"
},
"3": {
"internal_name": "normal",
"name": "Normal",
"category": "Quality",
"category_name": "Category"
},
"4": {
"internal_name": "Rarity_Rare_Weapon",
"name": "Mil-Spec Grade",
"category": "Rarity",
"color": "4b69ff",
"category_name": "Quality"
},
"5": {
"internal_name": "WearCategory2",
"name": "Field-Tested",
"category": "Exterior",
"category_name": "Exterior"
}
},
"classid": "350462890"
},
"success": true
}
}
So does anyone have any idea how I can return the market_hash_name? also please take note, I am fairly new to using Node.js.
data.result['350462890'].market_hash_name

JSon Parsing not working

I am trying to parse JSON data from the flixter API to import it to my blog.
In the example below, I tried using JavaScript to output the cast info for the movie expendables.
My full goal would be to get it to output the information
"Sylvester Stallone as Barney Ross, Jason Statham as Lee Christmas" and so on.
Here is my jsFiddle http://jsfiddle.net/k3V9p/3/
var jsontext = '{
"cast": [{
"id": "162664630",
"name": "Sylvester Stallone",
"characters": ["Barney Ross"]
}, {
"id": "162653720",
"name": "Jason Statham",
"characters": ["Lee Christmas"]
}, {
"id": "162652223",
"name": "Jet Li",
"characters": ["Yin Yang"]
}, {
"id": "162664307",
"name": "Dolph Lundgren",
"characters": ["Gunnar Jensen"]
}, {
"id": "162670654",
"name": "Chuck Norris",
"characters": ["Booker"]
}, {
"id": "326392465",
"name": "Terry Crews",
"characters": ["Hale Caesar"]
}, {
"id": "770731413",
"name": "Randy Couture",
"characters": ["Toll Road"]
}, {
"id": "770833479",
"name": "Liam Hemsworth",
"characters": ["Billy the Kid"]
}, {
"id": "770704326",
"name": "Scott Adkins",
"characters": ["Hector"]
}, {
"id": "770670020",
"name": "Nan Yu",
"characters": ["Maggie"]
}, {
"id": "162670708",
"name": "Jean-Claude Van Damme",
"characters": ["Jean Vilain"]
}, {
"id": "162652509",
"name": "Bruce Willis",
"characters": ["Mr. Church"]
}, {
"id": "162662233",
"name": "Arnold Schwarzenegger",
"characters": ["Trench"]
}, {
"id": "489251774",
"name": "Amanda Ooms",
"characters": ["Pilar"]
}, {
"id": "377608335",
"name": "Charisma Carpenter",
"characters": ["Lacy"]
}, {
"id": "771417014",
"name": "Nikolette Noel",
"characters": ["Sophia"]
}],
"links": {
"rel": "http://api.rottentomatoes.com/api/public/v1.0/movies/771238417.json"
}
}';
var titles = JSON.parse(jsontext);
document.write(titles.cast);
The problem you have is with end of lines in your string literal. You can write them like this :
var jsontext = '{\
"cast": [{\
But in your case, it's not clear if you really need JSON, as you could directly create your object as
var titles = {
cast": [{
...
I would say that the first problem you have is the JSON.parsing (which dystroy has perfectly answered), after solving that you will have to deal with rendering which you could do like this: (demo)
var titles = {
"cast": [{
"id": "162664630", "name": "Sylvester Stallone", "characters": ["Barney Ross"]
}, {"id": "162653720", "name": "Jason Statham", "characters": ["Lee Christmas"]
}, {"id": "162652223", "name": "Jet Li", "characters": ["Yin Yang"]
}, {"id": "162664307", "name": "Dolph Lundgren", "characters": ["Gunnar Jensen"]
}, {"id": "162670654", "name": "Chuck Norris", "characters": ["Booker"]
}, {"id": "326392465", "name": "Terry Crews", "characters": ["Hale Caesar"]
}, {"id": "770731413", "name": "Randy Couture", "characters": ["Toll Road"]
}, {"id": "770833479", "name": "Liam Hemsworth", "characters": ["Billy the Kid"]
}, {"id": "770704326", "name": "Scott Adkins", "characters": ["Hector"]
}, {"id": "770670020", "name": "Nan Yu", "characters": ["Maggie"]
}, {"id": "162670708", "name": "Jean-Claude Van Damme", "characters": ["Jean Vilain"]
}, {"id": "162652509", "name": "Bruce Willis", "characters": ["Mr. Church"]
}, {"id": "162662233", "name": "Arnold Schwarzenegger", "characters": ["Trench"]
}, {"id": "489251774", "name": "Amanda Ooms", "characters": ["Pilar"]
}, {"id": "377608335", "name": "Charisma Carpenter", "characters": ["Lacy"]
}, {"id": "771417014", "name": "Nikolette Noel", "characters": ["Sophia"]
}],
"links": {
"rel": "http://api.rottentomatoes.com/api/public/v1.0/movies/771238417.json"
}
},
star,
staring = [];
for (star = 0; star < titles.cast.length; star++) {
staring.push(titles.cast[star].name + ' as ' + titles.cast[star].characters[0]);
}
document.getElementById('Credits').innerHTML = staring.join(', ');
You don't need to change what flixster api is returning to you.
The problem is you need to call the API directly... do not copy&paste the result.
See the usage here http://developer.rottentomatoes.com/docs/read/json/v10/examples
Just do the Ajax call and onSuccess (searchCallback in the example) you will have the data parsed in json already.

Categories

Resources