简体   繁体   English

在将unmarshal用作通用接口时如何验证JSON?

[英]How to validate JSON when using unmarshal into generic interface?

I want to validate byte array data if it contains valid JSON using unmarsall method into interface. 我想使用unmarsall方法进入接口来验证字节数组数据是否包含有效JSON。

package main

import (
    "encoding/json"
    "fmt"
)

func isJSON(s string) bool {
    var js map[string]interface{}

    return json.Unmarshal([]byte(s), &js) == nil
}

func main() {
    var tests = []string{
        `{"a":"b"}`,
        `[{"a":"b"},{"a":"b"}]`,
    }

    for _, t := range tests {
        fmt.Printf("isJSON(%s) = %v\n\n", t, isJSON(t))
    }

}

Both input test parameters are valid JSON strings, but it validate based on the interface 'map[string]interface{}' 这两个输入测试参数都是有效的JSON字符串,但它们基于接口“ map [string] interface {}”进行验证

{
    "a": "b"
}

[{
    "a": "b"
}, {
    "a": "b"
}]

I want to validate the JSON text. 我想验证JSON文本。 JSON text is a serialized object or array. JSON文本是序列化的对象或数组。 Hence looking for a solution which support all valid cases for JSON text as I added test cases in playground . 因此,当我在操场上添加测试用例时,正在寻找一种支持所有有效的JSON文本用例的解决方案。

How can I make this interface ie var map[string]interface{} generic so it support both test cases of valid JSON string? 如何使该接口(即var map[string]interface{}通用,使其支持有效JSON字符串的两个测试用例?

Solved: Playground Link 解决:游乐场链接

Don't use map[string]interface{} but simply interface{} . 不要使用map[string]interface{}而只需使用interface{} The second example is of type []interface{} and there are more types of valid json. 第二个示例是[]interface{}类型,并且有更多类型的有效json。

Here your working code. 这是您的工作代码。 I added a few more cases of valid json. 我添加了更多有效的json案例。

playground 操场

Here the code if you want to allow only maps and slices: 如果您只允许使用地图和切片,请在以下代码中进行操作:

playground 操场

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM