如何在Typescript中解析JSON字符串

时间:2022-06-12 17:02:59

Is there a way to parse strings as JSON in Typescript.
Example: In JS, we can use JSON.parse(). Is there a similar function in Typescript?

有没有办法在Typescript中将字符串解析为JSON。示例:在JS中,我们可以使用JSON.parse()。在Typescript中有类似的功能吗?

I have a JSON object string as follows:

我有一个JSON对象字符串,如下所示:

'{"name": "Bob", "error": false}'

'{“name”:“Bob”,“error”:false}'

1 个解决方案

#1


51  

Typescript is (a superset of) javascript, so you just use JSON.parse as you would in javascript:

Typescript是javascript的(超集),所以你只需要像在javascript中一样使用JSON.parse:

let obj = JSON.parse(jsonString);

Only that in typescript you can have a type to the resulting object:

只有在打字稿中你可以为结果对象提供一个类型:

interface MyObj {
    myString: string;
    myNumber: number;
}

let obj: MyObj = JSON.parse('{ "myString": "string", "myNumber": 4 }');
console.log(obj.myString);
console.log(obj.myNumber);

(code in playground)

(游乐场代码)

#1


51  

Typescript is (a superset of) javascript, so you just use JSON.parse as you would in javascript:

Typescript是javascript的(超集),所以你只需要像在javascript中一样使用JSON.parse:

let obj = JSON.parse(jsonString);

Only that in typescript you can have a type to the resulting object:

只有在打字稿中你可以为结果对象提供一个类型:

interface MyObj {
    myString: string;
    myNumber: number;
}

let obj: MyObj = JSON.parse('{ "myString": "string", "myNumber": 4 }');
console.log(obj.myString);
console.log(obj.myNumber);

(code in playground)

(游乐场代码)