检查JSON是对象还是数组

问题描述 投票:4回答:3

Go中是否有一种简单的方法来检查给定的JSON是对象{}还是数组[]

我想到的第一件事就是将json.Unmarshal()变成一个界面,然后看它是变成地图还是一片地图。但这似乎效率很低。

我可以检查第一个字节是{还是[?或者是否存在已经存在的更好的方法。

json go unmarshalling
3个回答
7
投票

使用以下内容检测[]bytedata中的JSON文本是否为数组或对象:

 // Get slice of data with optional leading whitespace removed.
 // See RFC 7159, Section 2 for the definition of JSON whitespace.
 x := bytes.TrimLeft(data, " \t\r\n")

 isArray := len(x) > 0 && x[0] == '['
 isObject := len(x) > 0 && x[0] == '{'

这段代码处理可选的前导空格,并且比解组整个值更有效。

因为JSON中的顶级值也可以是数字,字符串,布尔值或者nil,所以isArrayisObject都可以评估为false。当JSON无效时,值isArrayisObject也可以评估为false。


2
投票

使用类型开关确定类型。这与Xay的答案类似,但更简单:

var v interface{}
if err := json.Unmarshal(data, &v); err != nil {
    // handle error
}
switch v := v.(type) {
case []interface{}:
    // it's an array
case map[string]interface{}:
    // it's an object
default:
    // it's something else
}

2
投票

使用json.Decoder逐步解析您的JSON。这比其他答案更有优势:

  1. 比解码整个值更有效
  2. 使用官方JSON解析规则,并在获得无效输入时生成标准错误。

请注意,此代码未经过测试,但应足以为您提供相关信息。如果需要,它还可以轻松扩展以检查数字,布尔值或字符串。

type jsonType(in io.Reader) (string, error) {
    dec := json.NewDecoder(in)
    // Get just the first valid JSON token from input
    t, err := dec.Token()
    if err != nil {
        return "", err
    }
    if d, ok := t.(json.Delim); ok {
        // The first token is a delimiter, so this is an array or an object
        switch (d) {
        case "[":
            return "array", nil
        case "{":
            return "object", nil
        default: // ] or }
            return nil, errors.New("Unexpected delimiter")
        }
    }
    return nil, errors.New("Input does not represent a JSON object or array")
}

请注意,这消耗了in的前几个字节。如有必要,读者可以进行复制。如果您尝试从字节切片([]byte)读取,请先将其转换为读取器:

t, err := jsonType(bytes.NewReader(myValue))
© www.soinside.com 2019 - 2024. All rights reserved.