duanbinren8906 2018-03-17 18:57
浏览 52
已采纳

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

I want to validate byte array data if it contains valid JSON using unmarsall method into interface.

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

", t, isJSON(t))
    }

}

Both input test parameters are valid JSON strings, but it validate based on the interface 'map[string]interface{}'

{
    "a": "b"
}

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

I want to validate the JSON text. JSON text is a serialized object or array. Hence looking for a solution which support all valid cases for JSON text as I added test cases in playground.

How can I make this interface i.e var map[string]interface{} generic so it support both test cases of valid JSON string?

Solved: Playground Link

  • 写回答

1条回答 默认 最新

  • douba4275 2018-03-17 19:04
    关注

    Don't use map[string]interface{} but simply interface{}. The second example is of type []interface{} and there are more types of valid json.

    Here your working code. I added a few more cases of valid json.

    playground

    Here the code if you want to allow only maps and slices:

    playground

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 支付宝批量检测实名工具
  • ¥15 基于单片机的靶位控制系统
  • ¥15 AT89C51控制8位八段数码管显示时钟。
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题