首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >解组嵌套的JSON对象

解组嵌套的JSON对象
EN

Stack Overflow用户
提问于 2014-01-22 04:05:59
回答 6查看 130.7K关注 0票数 145

topic上有a few questions,但似乎没有一个覆盖我的情况,因此我正在创建一个新的。

我有如下的JSON:

代码语言:javascript
复制
{"foo":{ "bar": "1", "baz": "2" }, "more": "text"}

有没有一种方法可以解组嵌套的bar属性,并将其直接分配给struct属性,而无需创建嵌套结构?

我现在采用的解决方案如下:

代码语言:javascript
复制
type Foo struct {
    More String `json:"more"`
    Foo  struct {
        Bar string `json:"bar"`
        Baz string `json:"baz"`
    } `json:"foo"`
    //  FooBar  string `json:"foo.bar"`
}

这是一个简化版本,请忽略详细信息。如您所见,我希望能够解析并将值赋给

代码语言:javascript
复制
//  FooBar  string `json:"foo.bar"`

我见过有人用地图,但这不是我的情况。我基本上不关心foo (它是一个大对象)的内容,除了一些特定的元素。

在这种情况下,正确的方法是什么?我不是在寻找奇怪的黑客,因此,如果这是一条可行的道路,我可以接受。

EN

回答 6

Stack Overflow用户

发布于 2016-06-06 20:50:39

这是一个如何从Safebrowsing JSON API sbserver代理服务器解组v4响应的示例:https://play.golang.org/p/4rGB5da0Lt

代码语言:javascript
复制
// this example shows how to unmarshall JSON requests from the Safebrowsing v4 sbserver
package main

import (
    "fmt"
    "log"
    "encoding/json"
)

// response from sbserver POST request
type Results struct {
    Matches []Match     
}

// nested within sbserver response
type Match struct {
    ThreatType string 
    PlatformType string 
    ThreatEntryType string 
    Threat struct {
        URL string
    }
}

func main() {
    fmt.Println("Hello, playground")

    // sample POST request
    //   curl -X POST -H 'Content-Type: application/json' 
    // -d '{"threatInfo": {"threatEntries": [{"url": "http://testsafebrowsing.appspot.com/apiv4/ANY_PLATFORM/MALWARE/URL/"}]}}' 
    // http://127.0.0.1:8080/v4/threatMatches:find

    // sample JSON response
    jsonResponse := `{"matches":[{"threatType":"MALWARE","platformType":"ANY_PLATFORM","threatEntryType":"URL","threat":{"url":"http://testsafebrowsing.appspot.com/apiv4/ANY_PLATFORM/MALWARE/URL/"}}]}`

    res := &Results{}
    err := json.Unmarshal([]byte(jsonResponse), res)
        if(err!=nil) {
            log.Fatal(err)
        }

    fmt.Printf("%v\n",res)
    fmt.Printf("\tThreat Type: %s\n",res.Matches[0].ThreatType)
    fmt.Printf("\tPlatform Type: %s\n",res.Matches[0].PlatformType)
    fmt.Printf("\tThreat Entry Type: %s\n",res.Matches[0].ThreatEntryType)
    fmt.Printf("\tURL: %s\n",res.Matches[0].Threat.URL)
}
票数 25
EN

Stack Overflow用户

发布于 2016-11-27 19:37:53

是。有了gjson,你现在要做的就是:

bar := gjson.Get(json, "foo.bar")

如果你愿意,bar可以是一个结构属性。还有,没有地图。

票数 24
EN

Stack Overflow用户

发布于 2015-11-22 05:43:17

那么匿名域呢?我不确定这是否会构成“嵌套结构”,但它比拥有嵌套结构声明要干净得多。如果您想在其他地方重用嵌套的元素,该怎么办?

代码语言:javascript
复制
type NestedElement struct{
    someNumber int `json:"number"`
    someString string `json:"string"`
}

type BaseElement struct {
    NestedElement `json:"bar"`
}
票数 9
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/21268000

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档