JSON.Parse在Faker.js中将字符串解析为JSOn时显示位置0处的错误

cha*_*tej 5 javascript json node.js faker

我已经看到了这些类型的问题并尝试了解决方案,但没有奏效.

我从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
Run Code Online (Sandbox Code Playgroud)

在Faker.js工作的预期代码是

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

如何处理这个问题.

Dap*_*que 0

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
Run Code Online (Sandbox Code Playgroud)