programing

중첩된 JSON 개체 표시 해제

elseif 2023. 3. 15. 19:24

중첩된 JSON 개체 표시 해제

가지 질문이 있습니다만, 어느 것 하나 제 케이스에 대응하지 않는 것 같아서, 새로운 것을 작성합니다.

다음과 같은 JSON이 있습니다.

{"foo":{ "bar": "1", "baz": "2" }, "more": "text"}

중첩된 막대 특성을 이동 해제하고 중첩된 구조를 작성하지 않고 구조물 특성에 직접 할당할 수 있는 방법이 있습니까?

현재 채택하고 있는 솔루션은 다음과 같습니다.

type Foo struct {
    More String `json:"more"`
    Foo  struct {
        Bar string `json:"bar"`
        Baz string `json:"baz"`
    } `json:"foo"`
    //  FooBar  string `json:"foo.bar"`
}

이것은 간결한 버전입니다만, 장황한 것은 무시해 주세요.보다시피 값을 해석하여

//  FooBar  string `json:"foo.bar"`

지도를 사용하는 사람들을 본 적은 있지만, 내 경우는 그렇지 않다.기본적으로는 의 내용에는 관심이 없습니다.foo(큰 오브젝트입니다만, 몇개의 특정 요소를 제외합니다).

이 경우 올바른 접근법은 무엇입니까?난 이상한 해커들을 찾는 게 아니니까, 이 방법이라면 난 괜찮아.

중첩된 막대 특성을 이동 해제하고 중첩된 구조를 작성하지 않고 구조물 특성에 직접 할당할 수 있는 방법이 있습니까?

아니요, encoding/json은 encoding/xml과 같이 ">some>deep>childnode"를 사용할 수 없습니다.네스트된 구조물이 좋은 방법입니다.

Volker가 언급한 것처럼, 중첩된 구조가 좋은 방법입니다.그러나 중첩된 구조를 원하지 않으면 UnmarshalJ를 재정의할 수 있습니다.SON 펑크

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

type A struct {
    FooBar string // takes foo.bar
    FooBaz string // takes foo.baz
    More   string 
}

func (a *A) UnmarshalJSON(b []byte) error {

    var f interface{}
    json.Unmarshal(b, &f)

    m := f.(map[string]interface{})

    foomap := m["foo"]
    v := foomap.(map[string]interface{})

    a.FooBar = v["bar"].(string)
    a.FooBaz = v["baz"].(string)
    a.More = m["more"].(string)

    return nil
}

제가 제대로 된 오류를 반환하지 않는다는 사실을 무시해 주세요.나는 단순함을 위해 그것을 생략했다.

업데이트: "추가" 값을 올바르게 검색하는 중입니다.

다음 예에서는 Safebrowsing v4 API sbserver 프록시 서버의 JSON 응답을 Marshall 해제하는 방법을 보여 줍니다.https://play.golang.org/p/4rGB5da0Lt

// 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)
}

, 이제 Gjson을 사용하면 됩니다.

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

bar구조적인 특성일 수도 있습니다.그리고 지도도 없어요

익명의 필드는 어떨까요?그것이 "귀한 구조"가 될지는 모르겠지만, 내포된 구조 선언을 하는 것보다 더 깨끗합니다.중첩된 요소를 다른 곳에서 재사용하려면 어떻게 해야 합니까?

type NestedElement struct{
    someNumber int `json:"number"`
    someString string `json:"string"`
}

type BaseElement struct {
    NestedElement `json:"bar"`
}

중첩된 값 할당json기본 json 키 유형을 알 때까지 구조화:-

package main

import (
    "encoding/json"
    "fmt"
)

// Object
type Object struct {
    Foo map[string]map[string]string `json:"foo"`
    More string `json:"more"`
}

func main(){
    someJSONString := []byte(`{"foo":{ "bar": "1", "baz": "2" }, "more": "text"}`)
    var obj Object
    err := json.Unmarshal(someJSONString, &obj)
    if err != nil{
        fmt.Println(err)
    }
    fmt.Println("jsonObj", obj)
}

이런 걸 하고 있었어요.하지만 프로토타입에서 생성된 구조물에서만 작동합니다.https://github.com/flowup-labs/grpc-utils

원어로

message Msg {
  Firstname string = 1 [(gogoproto.jsontag) = "name.firstname"];
  PseudoFirstname string = 2 [(gogoproto.jsontag) = "lastname"];
  EmbedMsg = 3  [(gogoproto.nullable) = false, (gogoproto.embed) = true];
  Lastname string = 4 [(gogoproto.jsontag) = "name.lastname"];
  Inside string  = 5 [(gogoproto.jsontag) = "name.inside.a.b.c"];
}

message EmbedMsg{
   Opt1 string = 1 [(gogoproto.jsontag) = "opt1"];
}

그러면 출력은 다음과 같습니다.

{
"lastname": "Three",
"name": {
    "firstname": "One",
    "inside": {
        "a": {
            "b": {
                "c": "goo"
            }
        }
    },
    "lastname": "Two"
},
"opt1": "var"
}

맵과 구조를 조합하면 키가 동적인 중첩된 JSON 개체를 마샬링 해제할 수 있습니다.=> 지도[문자열]

예: stock.json

{
  "MU": {
    "symbol": "MU",
    "title": "micro semiconductor",
    "share": 400,
    "purchase_price": 60.5,
    "target_price": 70
  },
  "LSCC":{
    "symbol": "LSCC",
    "title": "lattice semiconductor",
    "share": 200,
    "purchase_price": 20,
    "target_price": 30
  }
}

Go 어플리케이션

package main

import (
    "encoding/json"
    "fmt"
    "io/ioutil"
    "log"
    "os"
)

type Stock struct {
    Symbol        string  `json:"symbol"`
    Title         string  `json:"title"`
    Share         int     `json:"share"`
    PurchasePrice float64 `json:"purchase_price"`
    TargetPrice   float64 `json:"target_price"`
}
type Account map[string]Stock

func main() {
    raw, err := ioutil.ReadFile("stock.json")
    if err != nil {
        fmt.Println(err.Error())
        os.Exit(1)
    }
    var account Account
    log.Println(account)
}

해시의 동적 키는 문자열 처리이며 중첩된 개체는 구조체로 표시됩니다.

언급URL : https://stackoverflow.com/questions/21268000/unmarshaling-nested-json-objects