How to check string is in json format

后端 未结 8 1488
广开言路
广开言路 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条回答
  •  旧时难觅i
    2020-12-24 02:43

    Standard encoding/json library contains json.Valid function starting from go 1.9 - see https://github.com/golang/go/issues/18086 . This function may be used for checking whether the provided string is a valid json:

    if json.Valid(input) {
        // input contains valid json
    }
    

    But json.Valid may be quite slow comparing to third-party solutions such as fastjson.Validate, which is up to 5x faster than the standard json.Valid - see json validation section in benchmarks.

提交回复
热议问题