turn typescript object into json string turn typescript object into json string json json

turn typescript object into json string


Just use JSON.stringify(object). It's built into Javascript and can therefore also be used within Typescript.


You can use the standard JSON object, available in Javascript:

var a: any = {};a.x = 10;a.y='hello';var jsonString = JSON.stringify(a);


TS gets compiled to JS which then executed. Therefore you have access to all of the objects in the JS runtime. One of those objects is the JSON object. This contains the following methods:

  • JSON.parse() method parses a JSON string, constructing the JavaScript value or object described by the string.
  • JSON.stringify() method converts a JavaScript object or value to a JSON string.

Example:

const jsonString = '{"employee":{ "name":"John", "age":30, "city":"New York" }}';const JSobj = JSON.parse(jsonString);console.log(JSobj);console.log(typeof JSobj);const JSON_string = JSON.stringify(JSobj);console.log(JSON_string);console.log(typeof JSON_string);