I am trying to assign an array stored in json into an array in a controller when I press a button. I have run my json against several online validators and all of them claim my json is valid. However, when I go to parse it I get an unexpected token error.
I have double checked everything and I think everything closely mirrors the tutorial I am going through at https://docs.angularjs.org/tutorial/step_05 but it just doesn't want to work.
Relevant Controller Lines:
angular.module('myApp.controllers', [])
.controller('PlayerAdditionCtrl', function($scope, $http) {
$scope.players = [];
$scope.loadDefaults = function()
{
$http.get('defaults.json').success(function(array)
{
//assignment here
});
}
});
Complete json:
[
{
"name": "Mike",
"color": "teal"
},
{
"name": "Madre",
"color": "seagreen"
},
{
"name": "Anthony",
"color": "royalblue"
},
{
"name": "GI-Joe",
"color": "olivedrab"
}
]
Complete error text from chrome:
SyntaxError: Unexpected token {
at Object.parse (native)
at fromJson (http://localhost:8000/app/bower_components/angular/angular.js:1078:14)
at $HttpProvider.defaults.defaults.transformResponse (http://localhost:8000/app/bower_components/angular/angular.js:7317:18)
at http://localhost:8000/app/bower_components/angular/angular.js:7292:12
at Array.forEach (native)
at forEach (http://localhost:8000/app/bower_components/angular/angular.js:323:11)
at transformData (http://localhost:8000/app/bower_components/angular/angular.js:7291:3)
at transformResponse (http://localhost:8000/app/bower_components/angular/angular.js:7963:17)
at wrappedCallback (http://localhost:8000/app/bower_components/angular/angular.js:11319:81)
at http://localhost:8000/app/bower_components/angular/angular.js:11405:26 angular.js:9778
(anonymous function) angular.js:9778
(anonymous function) angular.js:7216
wrappedCallback angular.js:11322
(anonymous function) angular.js:11405
Scope.$eval angular.js:12412
Scope.$digest angular.js:12224
Scope.$apply angular.js:12516
done angular.js:8204
completeRequest angular.js:8412
xhr.onreadystatechange angular.js:8351
Check your json/and/or/pathtojson again your code works for me
http://plnkr.co/edit/AGdJ9SasmHn74RQe8xX2?p=preview
Related
I have the following code...
[
{
"number": 0,
"color": "blue",
"content": require('./first-card.pug')
}
...
]
When I try to run Webpack I see...
ERROR in ./src/app/jg/cards/cards.json
Module build failed: SyntaxError: Unexpected token r
at Object.parse (native)
Do I need to escape or something?
I'm trying to parse deploy but I'm getting an error. The global.json is:
{
"applications": {
”MyApp”: {
"applicationId": "7OI1Gk555Tr1CnrQ8bqplgImxMDJFTFfxaYUaPAZ",
"masterKey": "Udzp2AaPb7WLg3aYtHqRyShliJU3nV98ak3P6IGi"
},
"_default": {
"link": ”MyApp”
}
},
"global": {
"parseVersion": "1.3.1"
}
}
JSON Validator is giving me the error:
Parse error on line 2:
...cations": { ”MyApp”: {
----------------------^
Expecting 'STRING', '}'
instead of ”MyApp” use "MyApp" it will work fine.the first one is not parse-able to json because it will not treat it as string as shown in your error stated.
I need to have a generic JSON-representation of errors for any form that I have.
I have already read other solutions like in how to return json encoded form errors in symfony. But I don't want to create one more service for task that is already can be solved by other bundle that I connected to my project.
I use JMSSerializerBundle in my project and I know that this bundle can handle Symfony form errors using FormErrorHandler. But now I can get only whole form serialization:
$errors = $form->getErrors();
$serializer = $this->get('jms_serializer');
$json = $serializer->serialize($errors, 'json');
This code will return me next JSON-object:
{
"form": {
"children": {
"field1": [],
"field2": [],
"field_with_error": {
"errors": ["Error text"]
},
"collection": {
"child_form": [
{
"children": {
"field1": [],
"field2": []
}
}
]
}
}
},
"errors": []
}
But I need something like that (only fields with errors):
{
"field_with_error": {
"errors": ["Error text"]
}
}
How can I achieve that? I looked at FOSRestBundle that has already solved this problem. But I didn't find how they did it.
Using following code you can get errors the same structure you want:
$handler = new FormErrorHandler($this->get('translator'));
$visitor = new JsonSerializationVisitor(new SerializedNameAnnotationStrategy(new CamelCaseNamingStrategy()));
$errors = json_encode($handler->serializeFormToJson($visitor, $editForm, array()));
Result
"{"children":{"title":{"errors":["This value should not be blank."]},"summary":{"errors":["Give your post a summary!"]},"content":{"errors":["Your post should have some content!"]}}}"
jQuery Code:
$(document).ready(function(){
$.getJSON('dat.js', function(data) {
var obj = JSON.parse(data);
alert(obj[0].title);
});
});
My JSON file :
{
"posts":
[
{
"title": "ajax | Programming ",
"url": "hello"
},
{
"title": "jQuery and Ajax Demos Pard - 3",
"url": "how are you"
},
]
}
Its giving me an error JSON.parse:unexpected character. But when I tried to do it by taking the json inside an array its ok then. I want to access the data from json file itself
you do parseJSON when your input is a json string and u expect an object. Here, getJSON is already giving u the response as an object.
try this
$(document).ready(function(){
$.getJSON('dat.js', function(obj) {
alert(obj.posts[0].title);
});
});
A Quick jslint check says that you have invalid json at line 11 },, Try removing the comma from the last member of "posts" and see if that help
{
"title": "jQuery and Ajax Demos Pard - 3",
"url": "how are you"
}, <---- THIS
I got problem. I have this JSON automatically generated by Open Flash Chart php library. The problem is, OFC report JSON Parse Error [Syntax Error] while test result using http://www.jsonlint.com/ report that my JSON is fine. But, w3c parser report error too:(
Any help?
Here's the JSON:
{
"title": "Followers Trend",
"elements": [
{
"type": "area_hollow",
"fill-alpha": 0.35,
"values": [
],
"colour": "#5B56B6",
"text": "Followers",
"font-size": 12
}
],
"x_axis": {
"colour": "#A2ACBA",
"grid-colour": "#D7E4A3",
"offset": false,
"steps": 4,
"labels": {
"steps": 2,
"rotate": "vertical",
"colour": "#A2ACBA",
"labels": [
]
}
},
"x_legend": {
"text": "Week Trend (2009-08-17 - 2009-08-24)",
"style": "{font-size: 20px; color: #778877}"
},
"y_axis": {
"min": 0,
"max": 150,
"steps": 30
}
}
A few things I learned while playing with JSON is:
If you have validate the JSON on various JSON validation services and the result is GOOD. But, when you failed to eval it, try to wrap your JSON using ( and ) => ({jsondata})
var json = eval( "(" + jsonString + ")" );
NEVER build the JSON yourself. It's a gate to failure. Always use official or popular JSON library (depending on your language). For example:
On PHP: use json_encode()
On Java Android: use org.json.JSONObject
A list of all other available library to play with JSON is listed in JSON official page.
To display and format JSON data, you can use JSONViewer.
I think the w3c parser is having issues, I couldn't even get it to parse this:
{
"title" : "Followers Trend"
}
It gave me this error:
Validation errors:
lexer couldn't parse at "{
"title" : "Followers Trend"
}"
http://json.bloople.net helps you visualise the code to find and correct errors.
try this code, JSON.parse() method is not able to handle string which is in a
single quote as a value in the right-hand side. also if you want to handle the
UTF-8 character code, then it will do.
parseJSON = function() {
var data = {};
var reader = new FileReader();
reader.onload = function() {
try {
data = JSON.parse(reader.result.replace(/'/g, "\""));
console.log(data)
} catch (ex) {
console.log('error' + ex);
}
};
reader.readAsText(fileSelector_test[0].files[0], 'utf-8');
}