将类型脚本对象转换为 json 字符串

我试图用类型脚本初始化一个对象,它需要一个 JSON 字符串作为“ options”参数。确切地说,它是对象 给你。Options 参数必须是 JSON 字符串,而不是用于初始化 dijit 的对象。

有没有一种方法可以从一个类型脚本对象创建一个 JSON 字符串,而不需要手动操作?

请不要链接任何没有特别提到“ TypeScript”的问题,因为这个问题特别涉及到 TypeScript。虽然 JavaScript 的一个衍生物,你写代码的方式是不同的,因此这是唯一的问题,目前有关 TypeScript 的问题。

185801 次浏览

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);

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));

If you're using fs-extra, you can skip the JSON.stringify part with the writeJson function:

const fsExtra = require('fs-extra');


fsExtra.writeJson('./package.json', {name: 'fs-extra'})
.then(() => {
console.log('success!')
})
.catch(err => {
console.error(err)
})