说一个元素可以是单个项目还是数组,是有效的json(模式)吗? [英] Is it valid json (schema) to say that an element can be a single item or an array

查看:64
本文介绍了说一个元素可以是单个项目还是数组,是有效的json(模式)吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以指定一个特定的json值可以是单个元素还是数组?

Is it possible to specify that a particular json value can be either a single element or an array?

例如根据给定的单个json模式,以下两个json文档都可以有效吗?

E.g. Can both of following json documents be valid according to a given single json schema.

"person": {
    "name": "john",
    "friends": "jack"
}

"person": {
    "name": "john",
    "friends": ["jack", "jill"]
}

(我相信)如果您忽略模式的概念,并且仅在使用诸如rapidjson之类的解析器进行解析时,肯定有可能在读取内容之前简单地检查该元素是否为数组.

It's certainly possible (I believe) if you ignore the concept of schema, and simply when you are parsing using a parser such as rapidjson, to simply check if the element is an array or not before reading the contents.

我想知道的是,如果我采用这种方法,如果以后要为其指定json模式,会不会有问题?

What I want to know is, if I take this approach, will it be a problem if I want to specify a json schema for it later on?

推荐答案

在JSON模式中,您可以指定项目必须匹配的一个类型,或者项目必须匹配的类型数组至少一个(再加上其他几种可能性).

In JSON schema you can specify either one type that an item must match, or an array of types of which the item must match at least one (plus a few other possibilities).

是的,您可以有一个说明"friends"值为字符串或字符串数​​组的模式.

So yes, you can have a schema that says the "friends" value is either a string, or an array of strings.

显然,这意味着客户端代码和服务器代码需要区分两种情况,并且每种情况下都有不同的代码;您可能会考虑使用一个字符串发送一个数组,而不是某个人只有一个朋友来简化所有代码.

Obviously this means that client code and server code need to distinguish both cases and have different code for each case; you might consider sending an array with one string instead of someone has exactly one friend to simplify all code.

这篇关于说一个元素可以是单个项目还是数组,是有效的json(模式)吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆