简体   繁体   English

将 typescript 对象转换为 json 字符串

[英]turn typescript object into json string

I'm trying to initialize an object in typescript which requires a JSON string for the "options" parameter.我正在尝试在打字稿中初始化一个对象,它需要一个 JSON 字符串作为“选项”参数。 To be precise it is the object here .准确的说是 这里的对象。 The options parameter is required to be a JSON string and not an object for initializing the dijit. options 参数必须是 JSON 字符串,而不是用于初始化 dijit 的对象。

Is there a way to create a JSON string from a typescript object without it being a manual process?有没有办法从打字稿对象创建 JSON 字符串而不需要手动处理?

Please DO NOT link any questions which don't specifically say "TypeScript" as this question specifically relates to TypeScript.请不要链接任何没有特别提到“TypeScript”的问题,因为这个问题特别与 TypeScript 相关。 While a derivative of JavaScript the way that you write code is different and therefore this is the only post asking this question currently relating to TypeScript.虽然是 JavaScript 的衍生物,但你编写代码的方式是不同的,因此这是目前唯一一个与 TypeScript 相关的问题。

Just use JSON.stringify(object) .只需使用JSON.stringify(object) It's built into Javascript and can therefore also be used within Typescript.它内置于 Javascript 中,因此也可以在 Typescript 中使用。

You can use the standard JSON object, available in Javascript:您可以使用 Javascript 中可用的标准 JSON 对象:

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

TS gets compiled to JS which then executed. TS 被编译成 JS,然后执行。 Therefore you have access to all of the objects in the JS runtime.因此,您可以访问 JS 运行时中的所有对象。 One of those objects is the JSON object.这些对象之一是JSON对象。 This contains the following methods:这包含以下方法:

  • JSON.parse() method parses a JSON string, constructing the JavaScript value or object described by the string. JSON.parse()方法解析 JSON 字符串,构造字符串描述的 JavaScript 值或对象。
  • JSON.stringify() method converts a JavaScript object or value to a JSON string. JSON.stringify()方法将 JavaScript 对象或值转换为 JSON 字符串。

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.使用这些 JSON.(parse/stringify) 方法时要小心。 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:如果您使用fs-extra ,则可以使用writeJson函数跳过JSON.stringify部分:

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM