如何检查字符串是否为json格式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22128282/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to check string is in json format
提问by A-letubby
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.
我想创建一个函数来接收一个输入字符串,它可以是 json 格式的字符串或只是一个字符串。例如,像下面的函数一样简单。
func checkJson(input string){
if ... input is in json ... {
fmt.Println("it's json!")
} else {
fmt.Println("it's normal string!")
}
}
回答by William King
For anyone else looking for a way to validate any JSON string regardless of schema, try the following:
对于正在寻找验证任何 JSON 字符串而不考虑架构的方法的其他人,请尝试以下操作:
func IsJSON(str string) bool {
var js json.RawMessage
return json.Unmarshal([]byte(str), &js) == nil
}
回答by Cory LaNou
I was unclear if you needed to know about just a "quoted string" or if you needed to know about json, or the difference between both of them, so this shows you how to detect both scenarios so you can be very specific.
我不清楚您是否只需要了解“带引号的字符串”,或者您是否需要了解 json,或者两者之间的区别,因此这向您展示了如何检测这两种情况,以便您可以非常具体。
I posted the interactive code sample here as well: http://play.golang.org/p/VmT0BVBJZ7
我也在这里发布了交互式代码示例:http: //play.golang.org/p/VmT0BVBJZ7
package main
import (
"encoding/json"
"fmt"
)
func isJSONString(s string) bool {
var js string
return json.Unmarshal([]byte(s), &js) == nil
}
func isJSON(s string) bool {
var js map[string]interface{}
return json.Unmarshal([]byte(s), &js) == nil
}
func main() {
var tests = []string{
`"Platypus"`,
`Platypus`,
`{"id":"1"}`,
}
for _, t := range tests {
fmt.Printf("isJSONString(%s) = %v\n", t, isJSONString(t))
fmt.Printf("isJSON(%s) = %v\n\n", t, isJSON(t))
}
}
Which will output this:
这将输出:
isJSONString("Platypus") = true
isJSON("Platypus") = false
isJSONString(Platypus) = false
isJSON(Platypus) = false
isJSONString({"id":"1"}) = false
isJSON({"id":"1"}) = true
回答by peterSO
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
回答by valyala
Standard encoding/jsonlibrary contains json.Validfunction 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:
标准encoding/json库包含从 go 1.9 开始的json.Valid函数 - 请参阅https://github.com/golang/go/issues/18086。此函数可用于检查提供的字符串是否为有效的 json:
if json.Valid(input) {
// input contains valid json
}
But json.Validmay 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 validationsection in benchmarks.
但json.Valid与第三方解决方案(例如fastjson.Validate )相比,速度可能相当慢,后者比标准快 5 倍json.Valid- 请参阅benchmarksjson validation部分。
回答by Adi Sivasankaran
The current accepted answer (as of July 2017) fails for JSON arrays and hasn't been updated: https://repl.it/J8H0/10
当前接受的答案(截至 2017 年 7 月)对于 JSON 数组失败且尚未更新:https: //repl.it/J8H0/10
Try this:
尝试这个:
func isJSON(s string) bool {
var js interface{}
return json.Unmarshal([]byte(s), &js) == nil
}
Or William King's solution, which is better.
或者威廉金的解决方案,哪个更好。
回答by tatertot
In searching for an answer to this question, I found https://github.com/asaskevich/govalidator, which was tied to this blog post which describes creating an input validator: https://husobee.github.io/golang/validation/2016/01/08/input-validation.html. Just in case someone is looking for a quick library on doing this, I thought it would be useful to put that tool in an easy-to-find place.
在寻找这个问题的答案时,我找到了https://github.com/asaskevich/govalidator,它与这篇描述创建输入验证器的博客文章相关联:https: //husobee.github.io/golang/validation /2016/01/08/input-validation.html。以防万一有人正在寻找一个快速库来执行此操作,我认为将该工具放在易于找到的地方会很有用。
This package uses the same method for isJSON that William King suggests, as follows:
这个包对 isJSON 使用威廉金建议的相同方法,如下所示:
// IsJSON check if the string is valid JSON (note: uses json.Unmarshal).
func IsJSON(str string) bool {
var js json.RawMessage
return json.Unmarshal([]byte(str), &js) == nil
}
This package gave me some greater insight into JSON in go, so it seemed useful to put here.
这个包让我对 Go 中的 JSON 有了更深入的了解,所以把它放在这里似乎很有用。
回答by ymg
how about you use something like this:
你如何使用这样的东西:
if err := json.Unmarshal(input, temp_object); err != nil {
fmt.Println("it's normal string!")
} else {
fmt.Println("it's json!")
}

