JSON.Parse Showing error at position 0 when parsing a string in JSOn in Faker.js

I saw such questions and tried solutions, but did not work.

I send an array from the UI to the controller, there I have a link for faker.js in Node.js

My code in the controller:

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 

Expected code to work in Faker.js

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

How to approach this.

+5
source share
1 answer

JSON.stringify add additional "around all keys", you cannot delete them with Usercheck.replace (/ [''] + / g, ''), otherwise you cannot parse it:

 var a = JSON.stringify({e:5}) console.log(a) // {"e":5} JSON.parse(a); // ok JSON.parse("{e:5}"); // nok 
0
source

Source: https://habr.com/ru/post/1273705/


All Articles