英文:
How to check string is in json format
问题
我想创建一个函数来接收一个输入字符串,该字符串可以是 JSON 格式的字符串,也可以是普通字符串。例如,像下面这个简单的函数:
func checkJson(input string){
if ... input is in json ... {
fmt.Println("it's json!")
} else {
fmt.Println("it's normal string!")
}
}
我帮你翻译了一下,希望对你有帮助。
英文:
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.
func checkJson(input string){
if ... input is in json ... {
fmt.Println("it's json!")
} else {
fmt.Println("it's normal string!")
}
}
答案1
得分: 78
以下是验证任意 JSON 字符串的方法,无论其模式如何:
func IsJSON(str string) bool {
var js json.RawMessage
return json.Unmarshal([]byte(str), &js) == nil
}
这段代码可以用来判断一个 JSON 字符串是否有效。
英文:
For anyone else looking for a way to validate any JSON string regardless of schema, try the following:
func IsJSON(str string) bool {
var js json.RawMessage
return json.Unmarshal([]byte(str), &js) == nil
}
答案2
得分: 32
我不清楚你是只想了解"引号括起来的字符串"还是想了解JSON,或者两者之间的区别,所以这里展示了如何检测这两种情况,以便你可以非常具体地处理。
我也在这里发布了交互式的代码示例: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))
}
}
运行结果如下:
isJSONString("Platypus") = true
isJSON("Platypus") = false
isJSONString(Platypus) = false
isJSON(Platypus) = false
isJSONString({"id":"1"}) = false
isJSON({"id":"1"}) = true
英文:
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.
I posted the interactive code sample here as well: 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
答案3
得分: 26
标准的encoding/json
库从Go 1.9开始包含了json.Valid函数,可以用来检查提供的字符串是否是有效的JSON:
if json.Valid(input) {
// input包含有效的JSON
}
但是与第三方解决方案(如fastjson.Validate)相比,json.Valid
可能会比较慢,后者比标准的json.Valid
快5倍 - 参见基准测试中的json validation
部分。
英文:
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.
答案4
得分: 7
例如,
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`))
}
输出:
true
false
英文:
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
答案5
得分: 4
这可能是一个对标准库中实际函数的较旧的帖子。
但是你可以直接使用"encoding/json"包中的json.Valid()函数。
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)))
}
示例:https://play.golang.org/p/nfvOzQB919s
英文:
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)))
}
答案6
得分: 1
在寻找答案的过程中,我发现了https://github.com/asaskevich/govalidator,它与这篇博文相关,该博文描述了如何创建一个输入验证器:https://husobee.github.io/golang/validation/2016/01/08/input-validation.html。以防有人正在寻找一个快速的库来完成这个任务,我认为将这个工具放在一个易于找到的地方会很有用。
这个包使用了与William King建议的isJSON方法相同的方法,如下所示:
// IsJSON检查字符串是否是有效的JSON(注意:使用json.Unmarshal)。
func IsJSON(str string) bool {
var js json.RawMessage
return json.Unmarshal([]byte(str), &js) == nil
}
这个包让我对go中的JSON有了更深入的了解,所以我觉得把它放在这里很有用。
英文:
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.
This package uses the same method for isJSON that William King suggests, as follows:
// 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.
答案7
得分: 1
当前接受的答案(截至2017年7月)对于JSON数组无效,并且没有更新:https://repl.it/J8H0/10
尝试这个:
func isJSON(s string) bool {
var js interface{}
return json.Unmarshal([]byte(s), &js) == nil
}
或者使用William King的解决方案,这个更好。
英文:
The current accepted answer (as of July 2017) fails for JSON arrays and hasn't been updated: 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.
答案8
得分: 0
你可以尝试使用以下代码:
if err := json.Unmarshal(input, temp_object); err != nil {
fmt.Println("这是普通字符串!")
} else {
fmt.Println("这是 JSON!")
}
这段代码会尝试将输入解析为 JSON 对象,如果解析失败则输出"这是普通字符串!",否则输出"这是 JSON!"。
英文:
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!")
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论