[英]SyntaxError: Unexpected token { in JSON at position 1
我正在嘗試獲取具有內部對象且沒有密鑰的JSON請求。 但是我在位置1收到了意外令牌{
下面給出了示例JSON。
{{“” empid“:” 001“,” academictype“:”學士“,” academicdegree“:” BE“,” academicSpecialization“:”計算機科學“},{” empid“:” 002“,” academictype“:”碩士”,“學術學位”:“ MBA”,“ academicSpecialization”:“人力資源”}}
我試過下面的代碼
createEmployeeAcademics(req, res, next) {
let body = '';
var fbResponse = [];
req.on('data', function (chunk) {
console.log(chunk);
body += chunk;
console.log(body);
});
req.on('end', function () {
fbResponse.length = 0;
var arrayValues = JSON.parse(body);
for (var i = 0; i < arrayValues.length; i++) {
fbResponse.push(arrayValues[i]);
}
});
}
我低於錯誤
語法錯誤:意外令牌{在JSON.parse()位置1的JSON中
這是無效的Java腳本對象或列表,並且已經解析。 嘗試制作列表然后僅循環
喜歡
[ { "empid" : "001", "academictype": "Bachelor", "academicdegree": "BE", "academicSpecialization": "Computer Science" }, { "empid": "002", "academictype": "Masters", "academicdegree": "MBA", "academicSpecialization": "Human Resources" } ]
您收到Unexpected token
錯誤,因為JSON.parse(body)
無法解析您提供的JSON。 使用在線工具美化JSON可以更好地調試此問題。 為您的字符串:
{
{
"empid": "001",
"academictype": "Bachelor",
"academicdegree": "BE",
"academicSpecialization": "Computer Science"
}, {
"empid": "002",
"academictype": "Masters",
"academicdegree": "MBA",
"academicSpecialization": "Human Resources"
}
}
您的JSON缺少與objects
相關的重要屬性。
JSON對象用花括號{}包圍。
JSON對象以鍵/值對形式編寫。
您最外面的花括號后沒有任何鍵值對,而是直接從另一個對象開始。 您可以通過以下任一方法來更正JSON:
1.使外部JSON成為數組
[
{
"empid": "001",
...
}, {
"empid": "002",
...
}
]
數組可以直接將對象作為其子對象,並且可以順序訪問。
2.將鍵添加到外部對象的子對象:
{
"001": {
"academictype": "Bachelor",
"academicdegree": "BE",
"academicSpecialization": "Computer Science"
},
"002": {
"academictype": "Masters",
"academicdegree": "MBA",
"academicSpecialization": "Human Resources"
}
}
這樣,您可以使用對象的唯一ID(例如empid
)直接訪問對象,盡管遍歷對象可能不像數組那么容易。
您的示例JSON無效。 您可以使用json lint來驗證json對象。
您顯示的示例JSON無效。 如果那是您的服務器提供數據的方式,那么服務器正在提供格式錯誤的JSON。
您可能必須修復服務器才能以鍵值對格式發送數據。
有兩種方法可以做到這一點。
1)將雇員數組放在包裝對象中:
{"employees": [{ "empid" : "001", "academictype": "Bachelor", "academicdegree": "BE", "academicSpecialization": "Computer Science" }, { "empid": "002", "academictype": "Masters", "academicdegree": "MBA", "academicSpecialization": "Human Resources" }]}
2)放置由員工ID映射的員工:
{ "001":{ "empid" : "001", "academictype": "Bachelor", "academicdegree": "BE", "academicSpecialization": "Computer Science" }, "002":{ "empid": "002", "academictype": "Masters", "academicdegree": "MBA", "academicSpecialization": "Human Resources" } }
根據您選擇的格式,客戶端代碼將略有不同。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.