簡體   English   中英

JSON.Parse在Faker.js中將字符串解析為JSOn時顯示位置0處的錯誤

[英]JSON.Parse Showing error at position 0 while parsing string to JSOn in Faker.js

我已經看到了這些類型的問題並嘗試了解決方案,但沒有奏效。

我從UI發送一個數組到控制器,我在Node.js中有faker.js的參考

我在控制器中的代碼:

var FirstName = req.body;                    // req.body has array
console.log(FirstName);                      // **Prints** { FirstName: 'faker.name.firstName()' }
const User = FirstName;                     // Didnt work because faker.name.firstName is as string
const Usercheck = JSON.stringify(GettingData[0]);
var response = Usercheck.replace(/['"]+/g,'')
console.log(response);                      // Here it removed the quotations but took total as string. "{ FirstName: faker.name.firstName()}"
JSON.parse(response);     // Tried to parse string as JSON but this shows the error at position 0

在Faker.js工作的預期代碼是

const User = { FirstName: faker.name.firstName() } // Hard code and run this it is working fine

如何處理這個問題。

JSON.stringify添加額外的“圍繞所有鍵,你不能用Usercheck.replace(/ ['”] + / g,''刪除它們)否則你無法解析它:

var a = JSON.stringify({e:5})
console.log(a) // {"e":5}

JSON.parse(a); // ok
JSON.parse("{e:5}"); // nok

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM