Javascript 如何在 Typescript 中解析 JSON 字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38688822/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 21:43:15  来源:igfitidea点击:

How to parse JSON string in Typescript

javascriptjsonstringtypescript

提问by ssd20072

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}

回答by Nitzan Tomer

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

Typescript 是 javascript(的超集),因此您只需JSON.parse像在 javascript 中一样使用:

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)

操场上的代码

回答by chowey

If you want your JSON to have a validated Typescript type, you will need to do that validation work yourself. This is nothing new. In plain Javascript, you would need to do the same.

如果您希望 JSON 具有经过验证的 Typescript 类型,则需要自己进行验证工作。这不是什么新鲜事。在普通的 Javascript 中,你需要做同样的事情。

Validation

验证

I like to express my validation logic as a set of "transforms". I define a Descriptoras a map of transforms:

我喜欢将我的验证逻辑表示为一组“转换”。我将 a 定义Descriptor为转换映射:

type Descriptor<T extends Transformed> = {
  [P in keyof T]: (v: any) => T[P];
};

type Transformed = { [key: string]: any };

Then I can make a function that will apply these transforms to arbitrary input:

然后我可以创建一个函数,将这些转换应用于任意输入:

function pick<T extends Transformed>(v: any, d: Descriptor<T>): T {
  const ret: any = {};
  for (let key in d) {
    try {
      const val = d[key](v[key]);
      if (typeof val !== "undefined") {
        ret[key] = val;
      }
    } catch (err) {
      const msg = err instanceof Error ? err.message : String(err);
      throw new Error(`could not pick ${key}: ${msg}`);
    }
  }
  return ret;
}

Now, not only am I validating my JSON input, but I am building up a Typescript type as I go. The above generic types ensure that the result infers the types from your "transforms".

现在,我不仅在验证我的 JSON 输入,而且我正在构建一个 Typescript 类型。上述泛型类型确保结果从您的“转换”中推断出类型。

In case the transform throws an error (which is how you would implement validation), I like to wrap it with another error showing which key caused the error.

如果转换抛出错误(这就是您实现验证的方式),我喜欢用另一个错误包装它,显示哪个键导致了错误。

Usage

用法

In your example, I would use this as follows:

在您的示例中,我将按如下方式使用它:

const value = pick(JSON.parse('{"name": "Bob", "error": false}'), {
  name: String,
  error: Boolean,
});

Now valuewill be typed, since Stringand Booleanare both "transformers" in the sense they take input and return a typed output.

现在value将被输入,因为StringBoolean都是“转换器”,因为它们接受输入并返回输入输出。

Furthermore, the valuewill actually bethat type. In other words, if namewere actually 123, it will be transformed to "123"so that you have a valid string. This is because we used Stringat runtime, a built-in function that accepts arbitrary input and returns a string.

此外,value意志实际上是这种类型。换句话说,如果name实际上是123,它将被转换为,"123"以便您拥有有效的字符串。这是因为我们String在运行时使用了一个内置函数,它接受任意输入并返回一个string.

回答by Elisha Sterngold

There is a great library for it ts-json-object

有一个很棒的库ts-json-object

In your case you would need to run the following code:

在您的情况下,您需要运行以下代码:

import {JSONObject, required} from 'ts-json-object'

class Response extends JSONObject {
    @required
    name: string;

    @required
    error: boolean;
}

let resp = new Response({"name": "Bob", "error": false});

This library will validate the json before parsing

该库将在解析之前验证 json

回答by jfu

You can additionally use libraries that perform type validation of your json, such as Sparkson. They allow you to define a TypeScript class, to which you'd like to parse your response, in your case it could be:

您还可以使用执行 json 类型验证的库,例如Sparkson。它们允许你定义一个 TypeScript 类,你想解析你的响应,在你的情况下它可能是:

import { Field } from "sparkson";
class Response {
   constructor(
      @Field("name") public name: string,
      @Field("error") public error: boolean
   ) {}
}

The library will validate if the required fields are present in the JSON payload and if their types are correct. It can also do a bunch of validations and conversions.

该库将验证 JSON 负载中是否存在必需字段以及它们的类型是否正确。它还可以进行一堆验证和转换。