dousi5501 2016-11-04 18:11
浏览 54
已采纳

将字符串转换为json或struct

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

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

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

{ "votes": { "option_A": "3" }, "count": "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

  • 写回答

2条回答 默认 最新

  • 普通网友 2016-11-04 18:31
    关注

    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;

    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

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥20 测距传感器数据手册i2c