Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
I am trying to create a JSON and populate it with some data. The data is a bit complex so I would like to have its "title", "name" and "value".
My issue is that I am not able to get the content from the JSON I created and getting "Uncaught SyntaxError: Unexpected token o" error message. However, if I just pass the json variable to console.log() I can see all the objects contained in the variable.
Please see the code below:
JSON
var json = [
{"title":"rice",
"value":{
"carb": 44.5,
"fat": 0.1,
"cal": 205,
"prot": 4.3
}
},
{"title":"buckwheat",
"value":{
"carb": 20,
"fat": 1,
"cal": 92,
"prot": 3
}
},
{"title":"potato",
"value":{
"carb": 50.5,
"fat": 0.5,
"cal": 225,
"prot": 5.9
},
}
]
JS
var obj = JSON.parse(json);
console.log(obj[0].title);
Maybe I don't understand your question but
JSON.parse()
As first parameter takes some String, text value, converts and returns it as JSON object. Since you have one - you can populate it with your data.
Your json data is not valid.
Valid Example
You can press f12 in Chrome or Mozilla and look console. You can find what is wrong with your JS code.
[
{
"title": "rice",
"value": {
"carb": 20,
"fat": 1,
"cal": 92,
"prot": 3
}
},
{
"title": "buckwheat",
"value": {
"carb": 20,
"fat": 1,
"cal": 92,
"prot": 3
}
},
{
"title": "potato",
"value": {
"carb": 50.5,
"fat": 0.5,
"cal": 225,
"prot": 5.9
}
}
]
Your var "json" is already a javascript object. Just add a semicolon to it and fix the one error (comma after "prot": 5.9}) :
var obj = [
{"title":"rice",
"value":{
"carb": 44.5,
"fat": 0.1,
"cal": 205,
"prot": 4.3
}
},
{"title":"buckwheat",
"value":{
"carb": 20,
"fat": 1,
"cal": 92,
"prot": 3
}
},
{"title":"potato",
"value":{
"carb": 50.5,
"fat": 0.5,
"cal": 225,
"prot": 5.9
}
} ];
You can simply get the values with:
console.log(obj[0].title);
If you want to parse json, save your data in string format.
Related
This question already has answers here:
Get JavaScript object from array of objects by value of property [duplicate]
(17 answers)
Find object by id in an array of JavaScript objects
(36 answers)
Closed 2 years ago.
comment =[ {
"id": 4,
"snippetId": 1,
"text": "This code is correct but looks verbose. May be replace this hashset with an array so you can statically initialize?",
"line": 30,
"published_date": "2019-08-14T18:15:05.360241Z"
},
{
"id": 11,
"snippetId": 6,
"text": "On first glance, the code seems to be fine. But it assumes that first two numbers are each single-digit numbers. I think you should attempt to modify this method to include the more general case where first two numbers are multiple digits.",
"line": 4,
"published_date": "2019-08-15T00:36:55Z"
},
{
"id": 12,
"snippetId": 6,
"text": "indentation is off. Some interviewers may not like this.",
"line": 36,
"published_date": "2019-08-15T00:40:25.296813Z"
}
]
//this is my json
//please help how to filter the object who have snippetId = 6 (react js)
You should also study a bit more what a json is and how to use arrays in javascript though.
JSON.parse(comment).find(item => item.snippetId == 6)
comment = `[{
"id": 4,
"snippetId": 1,
"text": "This code is correct but looks verbose. May be replace this hashset with an array so you can statically initialize?",
"line": 30,
"published_date": "2019-08-14T18:15:05.360241Z"
},
{
"id": 11,
"snippetId": 6,
"text": "On first glance, the code seems to be fine. But it assumes that first two numbers are each single-digit numbers. I think you should attempt to modify this method to include the more general case where first two numbers are multiple digits.",
"line": 4,
"published_date": "2019-08-15T00:36:55Z"
},
{
"id": 12,
"snippetId": 6,
"text": "indentation is off. Some interviewers may not like this.",
"line": 36,
"published_date": "2019-08-15T00:40:25.296813Z"
}
]`;
console.log(JSON.parse(comment).find(item => item.snippetId == 6));
This question already has answers here:
Parse JSON in JavaScript? [duplicate]
(16 answers)
Closed 7 years ago.
I want to convert json to javascript array but its not working,
I tried the follwoing.
var arr = $.map(RatingGrade,function(value){ return value; });
var arr = Object.keys(RatingGrade).map(function(k) { return RatingGrade[k] });//not working on ie8
$.parse()
[{
"RGCode": 61,
"RGCode1": 61,
"ScoreMin": -1,
"ScoreMax": -1,
"GradeNo": "1+",
"GradeName": "Excellent",
"GradeDescription": "Excellent",
"createdby": 23,
"createdon": "/Date(1413970769020)/",
"updatedby": 23,
"updatedon": "/Date(1438628400000)/",
"status": "A",
"ScoreCardID": 1,
"PDLowerBound": 0,
"PDUpperBound": 0.03,
"MidPoint": 0.02,
"MaxPDMinPDDifference": 0.03,
"AveragePD": 0
}
]
how can i do this?also stringfy also but not working
What about?
JSON.parse('[{"RGCode": 61,"RGCode1": 61,"ScoreMin": -1,"ScoreMax": -1,"GradeNo": "1+","GradeName": "Excellent","GradeDescription": "Excellent","createdby": 23,"createdon": "/Date(1413970769020)/","updatedby": 23,"updatedon": "/Date(1438628400000)/","status": "A","ScoreCardID": 1,"PDLowerBound": 0,"PDUpperBound": 0.03,"MidPoint": 0.02, "MaxPDMinPDDifference": 0.03,"AveragePD": 0}]').forEach(function(item){
console.log(item);
});
This is an array. You just have to parse it.
Looks like map should do the job. Check the code and leave a comment if that does not work for you!
var data = {
"RGCode": 61,
"RGCode1": 61,
"ScoreMin": -1,
"ScoreMax": -1,
"GradeNo": "1+",
"GradeName": "Excellent",
"GradeDescription": "Excellent",
"createdby": 23,
"createdon": "/Date(1413970769020)/",
"updatedby": 23,
"updatedon": "/Date(1438628400000)/",
"status": "A",
"ScoreCardID": 1,
"PDLowerBound": 0,
"PDUpperBound": 0.03,
"MidPoint": 0.02,
"MaxPDMinPDDifference": 0.03,
"AveragePD": 0
}
var arr = Object.keys(data).map(function(T) {
return data[T]
});
console.log(arr);
I want to append following object array with existing one in angulajs for implementing load more feature.
ie,appending AJAX response with existing one each time.
I have one variable, $scope.actions which contains following JSON data,
{
"total": 13,
"per_page": 2,
"current_page": 1,
"last_page": 7,
"next_page_url": "http://invoice.local/activities/?page=2",
"prev_page_url": null,
"from": 1,
"to": 2,
"data": [
{
"id": 2108,
"action_type_id": 202,
"user_id": 1
},
{
"id": 2108,
"action_type_id": 202,
"user_id": 1
}
]
}
I want to append following JSON response each time this variable.
{
"data": [
{
"id": 2108,
"action_type_id": 202,
"user_id": 1
},
{
"id": 2108,
"action_type_id": 202,
"user_id": 1
}
]
}
I have tried with $scope.actions.data.concat(data.data);
but it is not working and getting following error message
$scope.actions.data.concat is not a function
You can use angular.extend(dest, src1, src2,...);
In your case it would be :
angular.extend($scope.actions.data, data);
See documentation here :
https://docs.angularjs.org/api/ng/function/angular.extend
Otherwise, if you only get new values from the server, you can do the following
for (var i=0; i<data.length; i++){
$scope.actions.data.push(data[i]);
}
This works for me :
$scope.array1 = $scope.array1.concat(array2)
In your case it would be :
$scope.actions.data = $scope.actions.data.concat(data)
$scope.actions.data.concat is not a function
same problem with me but i solve the problem by
$scope.actions.data = [].concat($scope.actions.data , data)
Simple
var a=[{a:4}], b=[{b:5}]
angular.merge(a,b) // [{a:4, b:5}]
Tested on angular 1.4.1
For one of my school projects, I have to create a game with Javascript. My Javascript experience is very minimal, and therefore I'm really stuck on how to create multiple levels within my game. With JSON, I load blocks for Mario to walk on:
createBlocks: function () {
console.log('game -> createBlocks');
$.getJSON('js/boxes.json', function (data) {
data.boxes.level1.forEach(function (blockData) {
this.stage.removeChild(this.block.el);
var block = new Block(blockData);
this.block.push(block);
this.stage.addChild(block.el);
}.bind(this));
}.bind(this));
}
With the function "createStars" the game loads another JSON. My goal is to have the game switch to another level with every 5 stars being collected. What is the best way to create this with JSON?
My JSON file for the blocks are created as follow:
{
"boxes": {
"level1": [
{
"x": 0,
"y": 115,
"width": 25,
"height": 25
},
{
"x": 25,
"y": 115,
"width": 25,
"height": 25
}
],
"level2": [
{
"x": 0,
"y": 95,
"width": 25,
"height": 25
}
]
}
}
Please let me know if you need my complete code to answer my question? I can also give a link to the game as it currently is hosted on my own site: http://school.carlavanloon.com/cp/
Furthermore, I'd like the game to stop the time after collecting 20 stars. This will then be the end time for the user of the game.
Many thanks in advance for your reply. And please let me know if I need to give any additional information.
Instead of making your json file around "boxes" you should design the json structure top down,
first load game json, which contains level objects - which contain boxes arrays etc. ie. something like this
var json = {
"game_data": {
"some_global_settings" : {"game_speed": 30, "theme": "dark"},
"level1": {
"boxes": [
{
"x": 0,
"y": 115,
"width": 25,
"height": 25
},
{
"x": 25,
"y": 115,
"width": 25,
"height": 25
}
],
"stars": [
{
"x": 0,
"y": 50,
"width": 25,
"height": 25
},
{
"x": 125,
"y": 120,
"width": 25,
"height": 25
}
],
"player_position" : {"x": 0,"y": 50},
"victory_condition" : {"stars_required" : 5, "time_limit" : "10min"}
},
"level2": {"same structure as above with different data" : 1}
}
}
and then make a level builder function which picks a level object and creates everything in it. To reload a new level, check the number of stars remaining, if its 0, call your createLevel(gamelevel) with n+1 for building the next level.
below is pseudo code sample.
Every time user collects a star, you will check if it was the last star required, and if so, increment the level counter and call level builder function which could be something like this
function buildLevel( levelNr ) {
var gdata = json.game_data["level"+levelNr];
//check if next level exists in game_data object
if (!gdata) {
finishGame();
return false;
}
//next level data exists, so build whats in it
//clear level from previous stuff
clearLevel();//perhaps replace canvas with new one
createBoxes( gdata.boxes);
createStars( gdata.stars);
createPlayer( gdata.player_position);
//everything is ready, add listeners / timers etc, and start the game
}
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to access a numeric property?
I write a page to access a api from other website.
it passes a json in the format of
{
"a": {
"2013-01-03": 3965,
"total": 52284,
"2013-01-05": 2636,
"2013-01-04": 4086
},
"b": {
"2013-01-03": 1969,
"total": 25594,
"2013-01-05": 1852,
"2013-01-04": 2031
},
"c": {
"2013-01-03": 6,
"total": 443,
"2013-01-05": 13,
"2013-01-04": 19
}
}
in my page, i try to access, for example data.a.total it will return 52284, but i cannot access data.a.2013-01-03, it will create an error. It seems that numbers cannot be the key for json. Can someone tell me whats the solution? thanks
You can read it as a['2012-12-13'] using the [] notation for accessing named properties.
For ex:
var data = {"a": {"2013-01-03": 3965, "total": 52284, "2013-01-05": 2636, "2013-01-04": 4086}, "b": {"2013-01-03": 1969, "total": 25594, "2013-01-05": 1852, "2013-01-04": 2031}, "c": {"2013-01-03": 6, "total": 443, "2013-01-05": 13, "2013-01-04": 19}};
data.a['2013-01-03'] will give you 3965
Use the square bracket notation if the keys contain characters that are not valid as JavaScript identifiers:
json.a["2013-01-03"] // 3965