DEV Community

Cover image for JSON + Javascript Cheatsheet.
manushifva
manushifva

Posted on

JSON + Javascript Cheatsheet.

Content

Convert array to JSON

var myArr = {
    key: value,
    key2: value2
};

var myJSON = JSON.stringify(myArr);
Enter fullscreen mode Exit fullscreen mode

Result:

'{"key":"value","key2":"value2"}';
Enter fullscreen mode Exit fullscreen mode

Parse JSON (convert from JSON to array)

var myJSON = '{"key":"value","key2":"value2"}';

var myArr = JSON.parse(myJSON);
Enter fullscreen mode Exit fullscreen mode

Result:

{
    key: value,
    key2: value2
};
Enter fullscreen mode Exit fullscreen mode

Count JSON array length

var myJSON = '{"key":"value","key2":"value2"}';

var myArr = JSON.parse(myJSON);

var jsonLength = myArr.length;
Enter fullscreen mode Exit fullscreen mode

Result:

2
Enter fullscreen mode Exit fullscreen mode

Do loop with JSON array

var myJSON = '{"key":"value","key2":"value2"}';

var myArr = JSON.parse(myJSON);

myArr.forEach(function(nowItem) {
    // Do things here
})
Enter fullscreen mode Exit fullscreen mode

Get data from JSON array

var myJSON = '{"key":"value","key2":"value2"}';

var myArr = JSON.parse(myJSON);

console.log(myArr["key2"]);
Enter fullscreen mode Exit fullscreen mode

Result:

value2
Enter fullscreen mode Exit fullscreen mode

Add item to JSON array

var myJSON = '{"key":"value","key2":"value2"}';

var myArr = JSON.parse(myJSON);

myArr["key3"] = "value3";
Enter fullscreen mode Exit fullscreen mode

myArr result:

{
    key: "value", 
    key2: "value2", 
    key3: "value3"
}
Enter fullscreen mode Exit fullscreen mode

Remove item from JSON array

var myJSON = '{"key":"value","key2":"value2"}';

var myArr = JSON.parse(myJSON);

delete myArr["key2"];
Enter fullscreen mode Exit fullscreen mode

myArr result:

{
   "key": "value"
}
Enter fullscreen mode Exit fullscreen mode

Discussion (0)