0

I have an instance of a Class named P

const stringifyObject = require('stringify-object');

JSON.parse(stringifyObject(P)); 

Which returns the following error:

_readableState: {
        ^

SyntaxError: Unexpected token _ in JSON at position 3
 at JSON.parse (<anonymous>)
3
  • 1
    Read the docs on JSON.parse. It will throw an exception if you pass an invalid JSON string into it. Commented Mar 24, 2019 at 19:50
  • OK, but how do I convert an Object into a string and back then? Commented Mar 24, 2019 at 19:59
  • pass a valid JSON string into it. Commented Mar 24, 2019 at 20:49

2 Answers 2

6

Object to string : JSON.stringify

var a = {a:"2da",b:"xfgsfg"}
console.log(JSON.stringify(a))

String to Object: JSON.parse

var s = '{"a":"2da","b":"xfgsfg"}';
console.log(JSON.parse(s))
Sign up to request clarification or add additional context in comments.

Comments

0

The NPM package stringify-object doesn't produce a JSON compliant string. You can use the built-in JSON.stringify to get a string, and JSON.parse to turn it back into an object.

const obj = {a: 1};
const str = JSON.stringify(obj); // '{"a":1}'
const deserialisedObj = JSON.parse(str); // {a: 1}
obj.a === deserialisedObj.a; // true

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.