I would recommend using JSON.stringify, which converts the set of the variables in the object to a JSON string.
var obj = {
name: 'myObj'
};
JSON.stringify(obj);
Most modern browsers support this method natively, but for those that don't, you can include a JS version.
Answer from Gary Chambers on Stack OverflowI would recommend using JSON.stringify, which converts the set of the variables in the object to a JSON string.
var obj = {
name: 'myObj'
};
JSON.stringify(obj);
Most modern browsers support this method natively, but for those that don't, you can include a JS version.
Use javascript String() function
String(yourobject); //returns [object Object]
or stringify()
JSON.stringify(yourobject)
Videos
Actually, the best solution is using JSON:
Documentation
JSON.parse(text[, reviver]);
Examples:
1)
var myobj = JSON.parse('{ "hello":"world" }');
alert(myobj.hello); // 'world'
2)
var myobj = JSON.parse(JSON.stringify({
hello: "world"
});
alert(myobj.hello); // 'world'
3) Passing a function to JSON
var obj = {
hello: "World",
sayHello: (function() {
console.log("I say Hello!");
}).toString()
};
var myobj = JSON.parse(JSON.stringify(obj));
myobj.sayHello = new Function("return ("+myobj.sayHello+")")();
myobj.sayHello();
Your string looks like a JSON string without the curly braces.
This should work then:
obj = eval('({' + str + '})');
WARNING: this introduces significant security holes such as XSS with untrusted data (data that is entered by the users of your application.)
If your object is like
const obj = { name: "John", age: 30, city: "New York" };
Use the JavaScript function JSON.stringify() to convert it into a string.
Like this JSON.stringify(obj).
then you will get this string:
"{"name":"John","age":30,"city":"New York"}"
let toString = ({name, age, language}) => `name: ${name}, age: ${age}, language: ${language}`;
const david = { name: 'David', age: 22, language: 'PHP' };
console.log(toString(david));
If you'd like to be more generic:
let toString = obj => Object.entries(obj).map(([k, v]) => `${k}: ${v}`).join(', ');
const david = { name: 'David', age: 22, language: 'PHP', favoriteFood: 'blue' };
console.log(toString(david));