john john - 25 days ago 7
Javascript Question

Uncaught syntaxerror unexpected token { in JSON

I receive this bug when using method POST. Please help me.

angular_min.js:114 SyntaxError: Unexpected token { in JSON at position 71
at JSON.parse (<anonymous>)
at wc (angular_min.js:16)
at cc (angular_min.js:88)
at angular_min.js:89
at n (angular_min.js:7)
at hd (angular_min.js:89)
at c (angular_min.js:91)
at angular_min.js:126
at m.$eval (angular_min.js:141)
at m.$digest (angular_min.js:138)


My code:
var json=
{parameter_name:"amount","parameter_value":$scope.it.amount};

var arr=[];
arr.push(json);
$scope.object={formula:$scope.it.formula_saving_point};
$scope.companyTemp={company_id:com_id};
var url = API_URL + "cumulative_point_formula";
var cmd = "check_formula";
var jsonFinal = JSON.stringify({json_parameter: JSON.parse(JSON.stringify(arr)),
company: JSON.parse(JSON.stringify($scope.companyTemp)),
cumulative_point_formula: JSON.parse(JSON.stringify($scope.object))});


This log jsonFinal

{"json_parameter":[{"parameter_name":"amount","parameter_value":"111111111"}],"company":{"company_id":40743},"cumulative_point_formula":{"formula":"amount/10000"}}


This is method POST:

$http({
method: 'POST',
url: url,
data: $.param({cm: cmd, dt: jsonFinal}),
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).success(function (response) {
console.log("success");
});


How to fix this bug?

Answer

If you take a closer look to your error it originated from JSON.parse and not $http. I believe this error is being caused by this line

var jsonFinal = JSON.stringify({json_parameter: JSON.parse(JSON.stringify(arr)),
    company: JSON.parse(JSON.stringify($scope.companyTemp)),
    cumulative_point_formula: JSON.parse(JSON.stringify($scope.object))});

where this chunk of code here is pretty redundant:

JSON.parse(JSON.stringify($scope.companyTemp))

stringify > parse would result the same as $scope.companyTemp and so are the others and as the same as this:

  var jsonFinal = JSON.stringify({
      json_parameter: arr,
      company: $scope.companyTemp,
      cumulative_point_formula: $scope.object
  });

JSON.parse converts JSON string to a valid JavaScript object

JSON.stringify converts JavaScript object to string

If it still produces an error I believe one of these three arr, $scope.companyTemp, $scope.object has an invalid value.

Hope that helps

Comments