将字符串转换为 json 或 struct

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/40429296/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 18:41:42  来源:igfitidea点击:

Converting string to json or struct

jsongo

提问by Leticia Esperon

I want to get a string that represents a json like this one:

我想得到一个表示这样的 json 的字符串:

{ "votes": { "option_A": "3" } }

{“投票”:{“option_A”:“3”}}

and include a "count" key in itso it ends like this:

并在其中包含一个“计数”键,因此它以这样的方式结束:

{ "votes": { "option_A": "3" }, "count": "1" }

{“投票”:{“option_A”:“3”},“计数”:“1”}

This is why I planned to convert it to json so I could add the count and then make it a string again. The problem is I don't know the structure of that json, so I can't use json.Unmarshal(in, &myStruct)because that struct varies. How can I do this? Thank you very much

这就是为什么我计划将其转换为 json 以便我可以添加计数然后再次将其设为字符串的原因。问题是我不知道那个 json 的结构,所以我不能使用,json.Unmarshal(in, &myStruct)因为那个结构不同。我怎样才能做到这一点?非常感谢

回答by fsenart

package main

import "encoding/json"

func main() {
    in := []byte(`{ "votes": { "option_A": "3" } }`)
    var raw map[string]interface{}
    if err := json.Unmarshal(in, &raw); err != nil {
        panic(err)
    }
    raw["count"] = 1
    out, err := json.Marshal(raw)
    if err != nil {
        panic(err)
    }
    println(string(out))
}

https://play.golang.org/p/o8ZwvgsQmoO

https://play.golang.org/p/o8ZwvgsQmoO

回答by evanmcdonnal

You really just need a single struct, and as mentioned in the comments the correct annotations on the field will yield the desired results. JSON is not some extremely variant data format, it is well defined and any piece of json, no matter how complicated and confusing it might be to you can be represented fairly easily and with 100% accuracy both by a schema and in objects in Go and most other OO programming languages. Here's an example;

你真的只需要一个结构体,正如评论中提到的,字段上的正确注释将产生所需的结果。JSON 不是某种极其多变的数据格式,它定义明确,任何 json 片段,无论对您来说多么复杂和令人困惑,都可以通过模式和 Go 中的对象以 100% 的准确度表示大多数其他面向对象编程语言。这是一个例子;

package main

import (
    "fmt"
    "encoding/json"
)

type Data struct {
    Votes *Votes `json:"votes"`
    Count string `json:"count,omitempty"`
}

type Votes struct {
    OptionA string `json:"option_A"`
}

func main() {
    s := `{ "votes": { "option_A": "3" } }`
    data := &Data{
        Votes: &Votes{},
    }
    err := json.Unmarshal([]byte(s), data)
    fmt.Println(err)
    fmt.Println(data.Votes)
    s2, _ := json.Marshal(data)
    fmt.Println(string(s2))
    data.Count = "2"
    s3, _ := json.Marshal(data)
    fmt.Println(string(s3))
}

https://play.golang.org/p/ScuxESTW5i

https://play.golang.org/p/ScuxESTW5i

Based on your most recent comment you could address that by using an interface{}to represent data besides the count, making the count a string and having the rest of the blob shoved into the interface{}which will accept essentially anything. That being said, Go is a statically typed language with a fairly strict type system and to reiterate, your comments stating 'it can be anything' are not true. JSON cannot be anything. For any piece of JSON there is schema and a single schema can define many many variations of JSON. I advise you take the time to understand the structure of your data rather than hacking something together under the notion that it cannot be defined when it absolutely can and is probably quite easy for someone who knows what they're doing.

根据您最近的评论,您可以通过使用 aninterface{}来表示除计数之外的数据,使计数成为字符串并将 blob 的其余部分推入interface{}其中,这将基本上接受任何内容。话虽如此,Go 是一种静态类型语言,具有相当严格的类型系统,重申一下,您说“它可以是任何东西”的评论是不正确的。JSON 不能是任何东西。对于任何 JSON 片段,都有架构,并且单个架构可以定义 JSON 的许多变体。我建议您花点时间了解数据的结构,而不是将某些东西拼凑在一起,因为它绝对可以定义,并且对于知道自己在做什么的人来说可能很容易。