turn typescript object into json string
Just use JSON.stringify(object)
. It's built into Javascript and can therefore also be used within Typescript.
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);
You can use the standard JSON object, available in Javascript:
var a: any = {};
a.x = 10;
a.y='hello';
var jsonString = JSON.stringify(a);
Be careful when using these JSON.(parse/stringify) methods. I did the same with complex objects and it turned out that an embedded array with some more objects had the same values for all other entities in the object tree I was serializing.
const temp = [];
const t = {
name: "name",
etc: [{
a: 0
}],
};
for (let i = 0; i < 3; i++) {
const bla = Object.assign({}, t);
bla.name = bla.name + i;
bla.etc[0].a = i;
temp.push(bla);
}
console.log(JSON.stringify(temp));