"Go json.Valid()"의 두 판 사이의 차이

(새 문서: ==개요== ;Go isJSONString() <syntaxhighlight lang='go'> package main import ( "encoding/json" "fmt" ) func isJSONString(s string) bool { var js interface{} err := json.Unmars...)
 
잔글 (Jmnote님이 Go isJSONString() 문서를 Go json.Valid() 문서로 이동했습니다)
 
(같은 사용자의 중간 판 하나는 보이지 않습니다)
1번째 줄: 1번째 줄:
==개요==
==개요==
;Go isJSONString()
;Go json.Valid()


<syntaxhighlight lang='go'>
<syntaxhighlight lang='go'>
9번째 줄: 9번째 줄:
"fmt"
"fmt"
)
)
func isJSONString(s string) bool {
var js interface{}
err := json.Unmarshal([]byte(s), &js)
return err == nil
}


func main() {
func main() {
testStrings := []string{
goodJSON := `{"example": 1}`
// false
badJSON := `{"example":2:]}}`
"",
"[",
"<html></html>",
"{",
`{a:1,b:2,c:3}`,
`{"incomplete": "data"`,
 
// true
`{"name": "John", "age": 30}`,
`[{"name": "John"}, {"name": "Jane"}]`,
`"Just a string"`,
`12345`,
`true`,
`[]`,
`[1,2,3]`,
`{}`,
`{"a":1,"b":2,"c":3}`,
}


for _, str := range testStrings {
fmt.Println(json.Valid([]byte(goodJSON))) // true
if isJSONString(str) {
fmt.Println(json.Valid([]byte(badJSON)))  // false
fmt.Println("✔️", str)
} else {
fmt.Println("❌", str)
}
}
}
}
/*
❌ [
❌ <html></html>
❌ {
❌ {a:1,b:2,c:3}
❌ {"incomplete": "data"
✔️ {"name": "John", "age": 30}
✔️ [{"name": "John"}, {"name": "Jane"}]
✔️ "Just a string"
✔️ 12345
✔️ true
✔️ []
✔️ [1,2,3]
✔️ {}
✔️ {"a":1,"b":2,"c":3}
*/
</syntaxhighlight>
</syntaxhighlight>



2025년 2월 18일 (화) 16:34 기준 최신판

1 개요[ | ]

Go json.Valid()
Go
Copy
package main

import (
	"encoding/json"
	"fmt"
)

func main() {
	goodJSON := `{"example": 1}`
	badJSON := `{"example":2:]}}`

	fmt.Println(json.Valid([]byte(goodJSON))) // true
	fmt.Println(json.Valid([]byte(badJSON)))  // false
}


2 같이 보기[ | ]