How to check string is in json format

后端 未结 8 1491
广开言路
广开言路 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 02:35

    For example,

    package main
    
    import (
        "encoding/json"
        "fmt"
    )
    
    func isJSONString(s string) bool {
        var js string
        err := json.Unmarshal([]byte(s), &js)
        return err == nil
    }
    
    func main() {
        fmt.Println(isJSONString(`"Platypus"`))
        fmt.Println(isJSONString(`Platypus`))
    }
    

    Output:

    true
    false
    

提交回复
热议问题