user8303201
user8303201

Reputation:

Node.js convert Object to string and string to Object?

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>)

Upvotes: 0

Views: 13026

Answers (2)

Arjun Singh
Arjun Singh

Reputation: 312

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))

Upvotes: 6

Joey Ciechanowicz
Joey Ciechanowicz

Reputation: 3663

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

Upvotes: 0

Related Questions