How to check string is in json format

后端 未结 8 1486
广开言路
广开言路 2020-12-24 02:17

I want to create a function to receive an input string which can be string in json format or just a string. For example, something easy like following function.



        
8条回答
  •  粉色の甜心
    2020-12-24 03:00

    This might be an older post to the actual function in the standard library.

    But you can just use the json.Valid() function in the "encoding/json" package.

       var tests = []string{
        `"Platypus"`,
        `Platypus`,
        `{"id":"1"}`,
        `{"id":"1}`,
    }
    
    for _, t := range tests {
        fmt.Printf("is valid: (%s) = %v\n", t, json.Valid([]byte(t)))
        
    }
    

    example https://play.golang.org/p/nfvOzQB919s

提交回复
热议问题