JSON解析异常

{1}我有一个或可能有一个 JSON 字符串{2},我需要解析它并获得解析的整数。


我知道我做错了,但这是我到目前为止所拥有的:


package main


import (

    "fmt"

    "encoding/json"

)


func main(){

  jsonStr:="{1}"

  jsonData:=[]byte(jsonStr)

  var v uint

  json.Unmarshal(jsonData, &v)

  data:=v

  fmt.Println(data)

}

在此示例中,data变量应包含整数值 1 或 2(如果jsonStr值为{2}


根据我使用 JSON 和 Go 的经验,我通常使用一个结构并将其传递到 Unmarshalling 函数中,但我无法从该数据响应中创建一个结构。


我查看了 API 文档,没有找到没有结构的字符串解析的解决方案


守候你守候我
浏览 138回答 3
3回答

30秒到达战场

这似乎对我有用:import "regexp"re:=regexp.MustCompile("[0-9A-Za-z]+")val:=re.FindAllString(jsonStr,-1)[0]

陪伴而非守候

正如评论者所指出的,您的示例字符串不是有效的 JSON,因为用大括号分隔的 JSON 文档必须是具有键值对列表的对象(例如{"x":1},数字是普通的(例如2))。但是,这个简单的“大括号括起”符号integer” 可以通过多种方式轻松解析,最终通过检查OPEN_BRACE, DIGIT+, CLOSE_BRACE.下面的示例代码检查给定字符串的第一个符文是左大括号{,最后一个是右大括号},中间的所有内容都可以使用以下方法解析为整数strconv.ParseInt(...):func main() {&nbsp; ss := []string{"{1}", "{2}", "{-123}", "{foo}", "{10", "20}", "30"}&nbsp; for _, s := range ss {&nbsp; &nbsp; x, err := parseBraceNumber(s)&nbsp; &nbsp; fmt.Printf("s=%-10qx=%-10derr=%v\n", s, x, err)&nbsp; }&nbsp; // s="{1}"&nbsp; &nbsp; &nbsp;x=1&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;err=<nil>&nbsp; // s="{2}"&nbsp; &nbsp; &nbsp;x=2&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;err=<nil>&nbsp; // s="{-123}"&nbsp; x=-123&nbsp; &nbsp; &nbsp; err=<nil>&nbsp; // s="{foo}"&nbsp; &nbsp;x=0&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;err=invalid brace number "{foo}"&nbsp; // s="{10"&nbsp; &nbsp; &nbsp;x=0&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;err=invalid brace number "{10"&nbsp; // s="20}"&nbsp; &nbsp; &nbsp;x=0&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;err=invalid brace number "20}"&nbsp; // s="30"&nbsp; &nbsp; &nbsp; x=0&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;err=invalid brace number "30"}func parseBraceNumber(s string) (int64, error) {&nbsp; if len(s) < 3 || s[0] != '{' || s[len(s)-1] != '}' {&nbsp; &nbsp; return 0, fmt.Errorf("invalid brace number %q", s)&nbsp; }&nbsp; x, err := strconv.ParseInt(s[1:len(s)-1], 10, 64)&nbsp; if err != nil {&nbsp; &nbsp; return 0, fmt.Errorf("invalid brace number %q", s)&nbsp; }&nbsp; return x, nil}当然,其他策略也是可能的(例如使用正则表达式),最终由您决定哪种实现最适合您的用例。

德玛西亚99

正则表达式的一些替代方案因为它们占用大量资源并且往往比其他解决方案慢,为简洁起见忽略错误。实际上他们不会。package mainimport (&nbsp; &nbsp; "fmt"&nbsp; &nbsp; "strconv")func main() {&nbsp; &nbsp; str := "{1}"&nbsp; &nbsp; num, _ := strconv.ParseInt(string(str[1]), 10, 64)&nbsp; &nbsp; fmt.Println(num)}或者更强大的东西,不关心字段中的位数{}。package mainimport (&nbsp; &nbsp; "fmt"&nbsp; &nbsp; "strconv")func main() {&nbsp; &nbsp; str := "{341}"&nbsp; &nbsp; num, _ := strconv.ParseInt(string(str[1:len(str)-1]), 10, 64)&nbsp; &nbsp; fmt.Println(num)}显示正则表达式比其他解决方案慢多少的小型基准图像。当其他选项可用或性能不是问题/关注时,应使用它们。&nbsp;即使是这样的东西也会执行正则表达式var n stringfor _, r := range str {&nbsp; &nbsp; if unicode.IsDigit(r) {&nbsp; &nbsp; &nbsp; &nbsp; n += string(r)&nbsp; &nbsp; }}基准代码 https://goplay.space/#PLMtSrMTN9k
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go