DEV Community

Sanchit Gupta
Sanchit Gupta

Posted on

Snippets... JSON

https://www.apps4developers.com/json/

JSON String to JSON Object

const jsonString = `{"name":"Apps4Developers.com","url":"https://apps4developers.com","description":"A collection of web development tutorials and examples","author":{"name":"Apps4Developers.com","url":"https://apps4developers.com"}}`;
const jsonObj = JSON.parse(jsonString);

console.log(jsonObj);
Enter fullscreen mode Exit fullscreen mode

JSON Object to JSON String

const jsonObj = {
    "name": "Apps4Developers.com",
    "url": "https://apps4developers.com",
    "description": "A collection of web development tutorials and examples",
    "author": {
        "name": "Apps4Developers.com",
        "url": "https://apps4developers.com"
    }
};
const jsonString = JSON.stringify(jsonObj, null, 2);

console.log(jsonString);
Enter fullscreen mode Exit fullscreen mode

JSON Object to Base64 String

const jsonObj = {
    "name": "Apps4Developers.com",
    "url": "https://apps4developers.com",
    "description": "A collection of web development tutorials and examples",
    "author": {
        "name": "Apps4Developers.com",
        "url": "https://apps4developers.com"
    }
};
const jsonString = JSON.stringify(jsonObj);
const base64String = btoa(jsonString);

console.log(base64String);
Enter fullscreen mode Exit fullscreen mode

JSON Object to URL Parameter String

const jsonObj = {
    "name": "Apps4Developers.com",
    "url": "https://apps4developers.com"
};
const urlParams = new URLSearchParams(jsonObj).toString()

console.log(urlParams);
Enter fullscreen mode Exit fullscreen mode

JSON Object to YAML using yaml

Install yaml package from NPM, learn more about this package here.

npm install yaml
Enter fullscreen mode Exit fullscreen mode
import YAML from 'yaml';

const jsonObj = {
    "name": "Apps4Developers.com",
    "url": "https://apps4developers.com",
    "description": "A collection of web development tutorials and examples",
    "author": {
        "name": "Apps4Developers.com",
        "url": "https://apps4developers.com"
    }
};

const doc = new YAML.Document();
doc.contents = jsonObj;
yaml = doc.toString();

console.log(yaml);
Enter fullscreen mode Exit fullscreen mode

Top comments (0)