Are JSON schemas necessary for defining the structure of a JSON?

前端 未结 2 1356
庸人自扰
庸人自扰 2021-01-24 01:50

I am asking this because I see that the current JSON schema draft (http://json-schema.org/) proposes to have the schema of JSON in the following way:

for the JSON :

相关标签:
2条回答
  • 2021-01-24 02:38

    The JSON itself does not define the structure. For example, I could write:

    {
      "a": "string",
      "b": "another string"
    }
    

    That's also valid JSON - but it's "differently structured" JSON, because "b" is now a string. But your API might only accept JSON with a particular structure, so although it's valid JSON, it's not the shape you need.

    Now, do you need JSON Schema to define the structure of your JSON data? No. You could instead say:

    The value must be an object. It must have two properties:

    • "a" - must be a string
    • "b" - must be an integer

    A programmer could understand this very easily, with no squiggly brackets or anything.

    However, there are advantages to having a machine-readable description of the format, because it lets you automate various things (e.g. testing, generating documentation, generating code/classes, etc.)


    Edit: As pointed out in the comments, you can take the type information from some example data, and use that as a model for other data. In this case, you're basically using your example data as a super-basic schema.

    For very simple constraints (basic type), this works. However, how would you say that "b" has to be an integer instead of a float? How do you say that "b" must be > 0? How do you say that "a" must not be the empty string ("")?

    There are indeed tools that generate a basic JSON Schema from example data - however, the resulting schema usually requires a bit of tweaking to actually describe the format (e.g. min/max, required/optional properties, etc.).

    0 讨论(0)
  • 2021-01-24 02:48

    Until now have never been necessary and in the short term I don't think it gets to be.

    I personally like JSON because its simplicity, portability and flexibility.

    I don't see even major brands using that schema so until now they don't take its serious.

    0 讨论(0)
提交回复
热议问题