英文:
golang unencode string to be parsable into json
问题
如何使这个工作?
s, _ := url.QueryUnescape("%22%7B%5C%22sessionId%5C%22%3A%5C%225331b937-7b55-4c2d-798a-25e574a7e8af%5C%22%2C%5C%22userId%5C%22%3A2%2C%5C%22userName%5C%22%3A%5C%22datami_op%5C%22%2C%5C%22userEmail%5C%22%3A%5C%22datami_op%40example.com%5C%22%2C%5C%22userRoles%5C%22%3A%5B%5C%22operator%5C%22%5D%7D%22")
fmt.Println(s)
//s := "{\"sessionId\":\"5331b937-7b55-4c2d-798a-25e574a7e8af\",\"userId\":2,\"userName\":\"op\",\"userEmail\":\"datami_op@example.com\",\"userRoles\":[\"operator\"]}"
var i Info
err := json.Unmarshal([]byte(s), &i)
fmt.Println(i, err)
英文:
How do I get this to work?
s, _ := url.QueryUnescape("%22%7B%5C%22sessionId%5C%22%3A%5C%225331b937-7b55-4c2d-798a-25e574a7e8af%5C%22%2C%5C%22userId%5C%22%3A2%2C%5C%22userName%5C%22%3A%5C%22datami_op%5C%22%2C%5C%22userEmail%5C%22%3A%5C%22datami_op%40example.com%5C%22%2C%5C%22userRoles%5C%22%3A%5B%5C%22operator%5C%22%5D%7D%22")
fmt.Println(s)
//s := "{\"sessionId\":\"5331b937-7b55-4c2d-798a-25e574a7e8af\",\"userId\":2,\"userName\":\"op\",\"userEmail\":\"datami_op@example.com\",\"userRoles\":[\"operator\"]}"
var i Info
err := json.Unmarshal([]byte(s), &i)
fmt.Println(i, err)
答案1
得分: 1
你可以手动删除引号,就像你在评论中所做的那样,或者你可以首先将其解组为一个JSON字符串:
var unquote string
err := json.Unmarshal([]byte(s), &unquote)
fmt.Println(unquote, err)
var i Info
err = json.Unmarshal([]byte(unquote), &i)
fmt.Println(i, err)
英文:
You can either manually remove the quoting yourself, as you have in your comment, or you could unmarshal first as a json string:
var unquote string
err := json.Unmarshal([]byte(s), &unquote)
fmt.Println(unquote, err)
var i Info
err = json.Unmarshal([]byte(unquote), &i)
fmt.Println(i, err)
答案2
得分: 1
我相信这是你想要的代码:
func unmarshalJsonJson(inval string) (*Info, error) {
var s string
err := json.Unmarshal([]byte(inval), &s)
if err != nil {
return nil, err
}
info := new(Info)
err = json.Unmarshal([]byte(s), info)
if err != nil {
return nil, err
}
return info, nil
}
输出
main.Info{
SessionId: "5331b937-7b55-4c2d-798a-25e574a7e8af",
UserId: 2,
Username: "datami_op",
Email: "datami_op@example.com",
Roles: []string{"operator"},
}
请注意,这只是代码的翻译部分,不包括任何其他内容。
英文:
I believe this does what you want:
<kbd>GoPlay</kbd>
Essentially you implement unmarshalJsonJson
(clever name, I know)...
The function will unmarshal as a json string, then use that string in the Info unmarshalling.
func unmarshalJsonJson(inval string) (*Info, error) {
var s string
err := json.Unmarshal([]byte(inval), &s)
if err != nil {
return nil, err
}
info := new(Info)
err = json.Unmarshal([]byte(s), info)
if err != nil {
return nil, err
}
return info, nil
}
OUTPUT
main.Info{
SessionId:"5331b937-7b55-4c2d-798a-25e574a7e8af",
UserId:2,
Username:"datami_op",
Email:"datami_op@example.com",
Roles:[]string{"operator"},
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论