解码结构未知的JSON [英] Decode JSON with unknown structure

查看:71
本文介绍了解码结构未知的JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想获取一个表示像这样的json的字符串:

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

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

并包含一个计数"输入,这样就结束了:

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

这就是为什么我计划将其转换为json以便添加计数然后 再次使其成为字符串. 问题是我不知道它的结构 JSON ,因此我不能使用json.Unmarshal(in, &myStruct),因为该结构 有所不同.我该怎么办?

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?

推荐答案

您实际上只需要一个结构,如注释中所述,在字段上的正确注释将产生所需的结果. JSON并不是一种非常多种多样的数据格式,它定义明确,并且任何json片段,无论它多么复杂和令人困惑,都可以通过模式和Go和对象中的对象非常容易地以100%的精度表示.大多数其他的OO编程语言.这是一个例子;

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

根据您最近的评论,您可以通过使用interface{}代表计数以外的数据来解决此问题,将计数设为字符串,并将其余的blob推入interface{}中,这实际上将接受任何内容.话虽这么说,Go是一种具有相当严格的类型系统的静态类型语言,并且重申一下,您声明它可以是任何东西"的评论是不正确的. JSON不能是任何东西.对于任何JSON片段,都有一个模式,一个模式可以定义JSON的许多变体.我建议您花一些时间来理解数据的结构,而不是将某些东西混在一起,因为它们是绝对无法定义的,并且对于知道自己正在做的事情的人来说可能很容易.

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.

这篇关于解码结构未知的JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆