var obj = JSON.parse(string);
Where string is your json string.
Videos
All current browsers have native JSON support built in. So as long as you're not dealing with prehistoric browsers like IE6/7 you can do it just as easily as that:
var j = {
"name": "binchen"
};
console.log(JSON.stringify(j));
With JSON.stringify() found in json2.js or native in most modern browsers.
JSON.stringify(value, replacer, space) value any JavaScript value, usually an object or array. replacer an optional parameter that determines how object values are stringified for objects. It can be a function or an array of strings. space an optional parameter that specifies the indentation of nested structures. If it is omitted, the text will be packed without extra whitespace. If it is a number, it will specify the number of spaces to indent at each level. If it is a string (such as "\t" or " "), it contains the characters used to indent at each level.
In order to better understand how JSON.stringify works, I've been tasked with creating a function that can take either an array or an object literal and convert either one into a string. For example:
[10000, "kani"] --> " [10000,"kani"] "
{ a: "is for apple" } --> " {"a":"is for apple"} "
{ foo: true, bar: false, baz: null } --> "{"foo":true,"bar":false,"baz": null}"Also, the object keys need to be in quotation marks too. I've been wracking my brain trying think of a strategy and cannot come up with anything. I've tried using the reduce method, and was able to surround the keys with quotations using template literal syntax for some test cases but not all. And I can't figure out how to set the entire object, which is my accumulator, to either an object string '{ }' or an array string '[ ]' and still be able to update the value of accumulator as reduce iterates. Here's the code I've tried:
function stringMaker(input) {
input = Object.entries(input).reduce((accum, element) => {
let [key, value] = element;
accum["${key}"] = value;
return accum;
}, { } );
return input;
}
const object1 = {a: 'is for apple'};
console.log(stringMaker(object1)) --> {"a": 'is for apple'} //no quotation marks
const object2 = { foo: true, bar: false, baz: null }
console.log(stringMaker(object2)) --> {"foo": true, "bar": false, "baz": null} //no quotation marks
const object3 = {a:{"b":"c"}}
console.log(stringMaker(object3)) --> Object({ "a": Object({ b: 'c' }) }) --> expected '{"a":{"b":"c"}}'
//I have no idea what happened hereAs you can see my results are all over the place. I don't even know why the last case is returning Object. And I haven't even started testing with arrays yet. Advice/hints please!