잡히지 않은 구문 오류 : JSON.parse가있는 예기치 않은 토큰
세 번째 줄 에서이 오류의 원인은 무엇입니까?
var products = [{
"name": "Pizza",
"price": "10",
"quantity": "7"
}, {
"name": "Cerveja",
"price": "12",
"quantity": "5"
}, {
"name": "Hamburguer",
"price": "10",
"quantity": "2"
}, {
"name": "Fraldas",
"price": "6",
"quantity": "2"
}];
console.log(products);
var b = JSON.parse(products); //unexpected token o
콘솔을 열어 오류보기
products
객체입니다. (객체 리터럴에서 생성)
JSON.parse()
JSON 표기법이 포함 된 문자열 을 Javascript 객체로 변환하는 데 사용됩니다 .
코드는 객체를 .toString()
JSON 텍스트로 구문 분석하기 위해 객체를 문자열로 변환합니다 (을 호출하여 ).
기본값 .toString()
은을 반환 "[object Object]"
하며 이는 유효한 JSON이 아닙니다. 따라서 오류.
그것이 유효한 JSON이라는 것을 알고 있지만 여전히 이것을 얻고 있다고 가정 해 봅시다 ...
이 경우 문자열에 숨겨진 소스 / 특수 문자가있을 수 있습니다. 유효성 검사기에 붙여 넣으면 손실되지만 문자열에는 여전히 있습니다. 그 문자들은 보이지 않지만 깨질 것입니다JSON.parse()
경우 s
원시 JSON이며, 다음을 함께 정리 :
// preserve newlines, etc - use valid JSON
s = s.replace(/\\n/g, "\\n")
.replace(/\\'/g, "\\'")
.replace(/\\"/g, '\\"')
.replace(/\\&/g, "\\&")
.replace(/\\r/g, "\\r")
.replace(/\\t/g, "\\t")
.replace(/\\b/g, "\\b")
.replace(/\\f/g, "\\f");
// remove non-printable and other non-valid JSON chars
s = s.replace(/[\u0000-\u0019]+/g,"");
var o = JSON.parse(s);
객체 를 문자열 화 하려는 것 같습니다 . 이렇게하십시오 :
JSON.stringify(products);
오류의 이유 JSON.parse()
는 String
값 을 예상 하고 products
입니다 Array
.
참고 : 나는 이후 json.parse('[object Array]')
토큰 o
을 기대하지 않았다고 불평하는 것으로 생각합니다 [
.
와 동일한 문제를 발견했습니다 JSON.parse(inputString)
.
필자의 경우 입력 문자열이 내 서버 페이지에서 온다 [페이지 메소드 반환] .
인쇄했습니다 typeof(inputString)
-문자열이지만 여전히 오류가 발생합니다.
나는 또한 시도 JSON.stringify(inputString)
했지만 도움이되지 않았다.
나중에이 [\n]
필드 값 내에서 줄 바꾸기 연산자와 관련된 문제라는 것을 알았습니다 .
나는 [다른 문자 로 바꾸고, 구문 분석 후에 줄 바꿈을 다시 넣었습니다] 모든 것이 잘 작동합니다.
products = [{"name":"Pizza","price":"10","quantity":"7"}, {"name":"Cerveja","price":"12","quantity":"5"}, {"name":"Hamburguer","price":"10","quantity":"2"}, {"name":"Fraldas","price":"6","quantity":"2"}];
로 변경
products = '[{"name":"Pizza","price":"10","quantity":"7"}, {"name":"Cerveja","price":"12","quantity":"5"}, {"name":"Hamburguer","price":"10","quantity":"2"}, {"name":"Fraldas","price":"6","quantity":"2"}]';
JSON.parse가 문자열 입력 매개 변수를 기다리고 있습니다. 문제점을 해결하려면 JSON 오브젝트를 문자열 화해야합니다.
products = [{"name":"Pizza","price":"10","quantity":"7"}, {"name":"Cerveja","price":"12","quantity":"5"}, {"name":"Hamburguer","price":"10","quantity":"2"}, {"name":"Fraldas","price":"6","quantity":"2"}];
console.log(products);
var b = JSON.parse(JSON.stringify(products)); //solves the problem
선행 또는 후행 공백이 있으면 유효하지 않습니다. 후행 / 리딩 공간은 다음과 같이 제거 할 수 있습니다.
mystring = mystring.replace(/^\s+|\s+$/g, "");
출처 : http://www.toptip.ca/2010/02/javascript-trim-leading-or-trailing.html
[
{
"name": "Pizza",
"price": "10",
"quantity": "7"
},
{
"name": "Cerveja",
"price": "12",
"quantity": "5"
},
{
"name": "Hamburguer",
"price": "10",
"quantity": "2"
},
{
"name": "Fraldas",
"price": "6",
"quantity": "2"
}
]
파싱 할 수있는 완벽한 Json이 있습니다.
https://jsonformatter.curiousconcept.com/에 유효한 JSON 문자열이 있어야합니다.
유효한 json 문자열에는 큰 따옴표가 있어야합니다.
JSON.parse({"u1":1000,"u2":1100}) // will be ok
따옴표 없음 오류 발생
JSON.parse({u1:1000,u2:1100})
// error Uncaught SyntaxError: Unexpected token u in JSON at position 2
작은 따옴표는 오류를 일으킨다
JSON.parse({'u1':1000,'u2':1100})
// error Uncaught SyntaxError: Unexpected token ' in JSON at position 1
"SyntaxError: Unexpected token"
호출 할 때 예외 가 발생할 수있는 다른 문제 JSON.parse()
는 문자열 값에서 다음 중 하나를 사용하는 것입니다.
줄 바꿈 문자.
탭 (예, Tab 키로 생성 할 수있는 탭!)
모든 독립형 슬래시
\
(그러나 어떤 이유로 든/
Chrome에는 없습니다.)
전체 목록을 보려면 여기 에서 문자열 섹션을 참조하십시오 .
예를 들어 다음과 같은 경우이 예외가 발생합니다.
{
"msg" : {
"message": "It cannot
contain a new-line",
"description": "Some discription with a tabbed space is also bad",
"value": "It cannot have 3\4 un-escaped"
}
}
따라서 다음과 같이 변경해야합니다.
{
"msg" : {
"message": "It cannot\ncontain a new-line",
"description": "Some discription with a\t\ttabbed space",
"value": "It cannot have 3\\4 un-escaped"
}
}
말하자면, 더 많은 양의 텍스트를 JSON 전용 형식으로 읽을 수 없게 만듭니다.
POST 또는 PUT 방법을 사용하는 경우 본문 부분을 반드시 확인하십시오.
https://gist.github.com/manju16832003/4a92a2be693a8fda7ca84b58b8fa7154에 예제를 문서화했습니다.
이전 답변을 기반으로 한 기능은 다음과 같습니다. YMMV는 내 컴퓨터에서 작동합니다.
/**
* @description Converts a string response to an array of objects.
* @param {string} string - The string you want to convert.
* @returns {array} - an array of objects.
*/
function stringToJson(input) {
var result = [];
//replace leading and trailing [], if present
input = input.replace(/^\[/,'');
input = input.replace(/\]$/,'');
//change the delimiter to
input = input.replace(/},{/g,'};;;{');
// preserve newlines, etc - use valid JSON
//https://stackoverflow.com/questions/14432165/uncaught-syntaxerror-unexpected-token-with-json-parse
input = input.replace(/\\n/g, "\\n")
.replace(/\\'/g, "\\'")
.replace(/\\"/g, '\\"')
.replace(/\\&/g, "\\&")
.replace(/\\r/g, "\\r")
.replace(/\\t/g, "\\t")
.replace(/\\b/g, "\\b")
.replace(/\\f/g, "\\f");
// remove non-printable and other non-valid JSON chars
input = input.replace(/[\u0000-\u0019]+/g,"");
input = input.split(';;;');
input.forEach(function(element) {
// console.log(JSON.stringify(element));
result.push(JSON.parse(element));
}, this);
return result;
}
잘하면 이것은 다른 누군가를 돕습니다.
My issue was that I had commented HTML in a PHP callback function via AJAX that was parsing the comments and return invalid JSON.
Once I removed the commented HTML, all was good and the JSON was parsed with no issues.
products is an array which can be used directly:
var i, j;
for(i=0;i<products.length;i++)
for(j in products[i])
console.log("property name: " + j,"value: "+products[i][j]);
Now apparently \r
, \b
, \t
, \f
, etc aren't the only problematic chars that can give you this error.
Note that some browsers may have additional requirements for the input of JSON.parse
.
Run this test code on your browser:
var arr = [];
for(var x=0; x < 0xffff; ++x){
try{
JSON.parse(String.fromCharCode(0x22, x, 0x22));
}catch(e){
arr.push(x);
}
}
console.log(arr);
Testing on Chrome, I see that it doesn't allow JSON.parse(String.fromCharCode(0x22, x, 0x22));
where x
is 34, 92, or from 0 to 31.
Chars 34 and 92 are the "
and \
characters respectively, and they are usually expected and properly escaped. It's chars 0 to 31 that would give you problems.
To help with debugging, before you do JSON.parse(input)
, first verify that the input doesn't contain problematic characters:
function VerifyInput(input){
for(var x=0; x<input.length; ++x){
let c = input.charCodeAt(x);
if(c >= 0 && c <= 31){
throw 'problematic character found at position ' + x;
}
}
}
Why you need JSON.parse? It's already in array of object format.
Better use JSON.stringify as below : var b = JSON.stringify(products);
This may help you.
Oh man, solutions in all above answers provided so far didn't work for me. I had a similar problem just now. I managed to solve it with wrapping with the quote. See the screenshot. Whoo.
Original:
var products = [{
"name": "Pizza",
"price": "10",
"quantity": "7"
}, {
"name": "Cerveja",
"price": "12",
"quantity": "5"
}, {
"name": "Hamburguer",
"price": "10",
"quantity": "2"
}, {
"name": "Fraldas",
"price": "6",
"quantity": "2"
}];
console.log(products);
var b = JSON.parse(products); //unexpected token o
The error you are getting i.e. "unexpected token o" is because json is expected but object is obtained while parsing. That "o" is the first letter of word "object".
The only mistake you are doing is, you are parsing already parsed object so it's throwing error, use this and you will be good to go.
var products = [{
"name": "Pizza",
"price": "10",
"quantity": "7"
}, {
"name": "Cerveja",
"price": "12",
"quantity": "5"
}, {
"name": "Hamburguer",
"price": "10",
"quantity": "2"
}, {
"name": "Fraldas",
"price": "6",
"quantity": "2"
}];
console.log(products[0].name); //name of item at 0th index
if you want to print entire json then use JSON.stringify()
It can happen for a lot of reasons, but probably for an invalid char, so you can use JSON.stringify(obj);
that will turn your object into a JSON but remember that it is a JQUERY expression.
I have this error BECAUSE the API that returned the json object was giving AN ERROR (in my case Code Igniter, return an html when the php code fails) so IT'S NOT AN JSON OBJECT.
Check the SQL Sentences and the PHP code, and test it with Postman (or some other API tester)
Use eval
. It takes JavaScript expression/code as string and evaluates/executes it.
eval(inputString);
참고URL : https://stackoverflow.com/questions/14432165/uncaught-syntaxerror-unexpected-token-with-json-parse
'IT' 카테고리의 다른 글
brew installed Python을 기본 Python으로 어떻게 사용합니까? (0) | 2020.05.29 |
---|---|
SQL Server에서 저장 프로 시저 또는 함수의 마지막 변경 날짜를 확인하는 방법 (0) | 2020.05.29 |
알파벳순으로 목록을 정렬하려면 어떻게해야합니까? (0) | 2020.05.29 |
큰 Ө 표기법은 정확히 무엇을 의미합니까? (0) | 2020.05.29 |
ASP.NET MVC :이 개체에 대해 매개 변수가없는 생성자가 정의되어 있지 않습니다 (0) | 2020.05.29 |