JSON.Parse在Faker.js中将stringparsing为JSOn时,在位置0处显示错误
我已经看到了这些types的问题,并尝试解决scheme,但没有工作。
我从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,'')删除它们,否则你不能parsing它:
var a = JSON.stringify({e:5}) console.log(a) // {"e":5} JSON.parse(a); // ok JSON.parse("{e:5}"); // nok