亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

將 JSON 與數組轉換

將 JSON 與數組轉換

Go
慕村9548890 2023-08-14 17:45:37
我編寫了以下代碼來從 JSON 獲取數組,并且想要檢索類似的內容[{“id”:“id1”,“友好”:“友好1”},{“id”:“id2”,“友好”:“友好2”}]但它是空的:[{"id":"","friend":""},{"id":"","friend":""}]package mainimport (    "encoding/json"    "fmt")var input = `[            {                "not needed": "",                "_source": {                    "id": "id1",                    "friendly": "friendly1"                }            },            {                "_source": {                    "id": "id2",                    "friendly": "friendly2"                }            }]`type source struct {    Id string `json:"id"`    Friendly string `json:"friendly"`}func main() {    result := make([]source, 0)    sources := []source{}    json.Unmarshal([]byte(input), &sources)    for _, n := range sources {        result = append(result, n)    }    out, _ := json.Marshal(result)    fmt.Println(string(out))}
查看完整描述

1 回答

?
子衿沉夜

TA貢獻1828條經驗 獲得超3個贊

嘗試創建另一個結構體,其中有一個名為Sourcetype 的字段source。在下面的示例中,我將此稱為 struct outer。您的輸入應該是一個數組outer,您的結果應該是一個數組source。


像這樣的東西:



import (

    "encoding/json"

    "fmt"

)


var input = `[

            {

                "not needed": "",

                "_source": {

                    "id": "id1",

                    "friendly": "friendly1"

                }

            },

            {

                "_source": {

                    "id": "id2",

                    "friendly": "friendly2"

                }

            }]`


type outer struct {

    Source source `json:"_source"`

}


type source struct {

    Id string `json:"id"`

    Friendly string `json:"friendly"`

}


func main() {

    result := make([]source, 0)

    sources := []outer{}


    json.Unmarshal([]byte(input), &sources)


    for _, n := range sources {

        result = append(result, n.Source)

    }

    out, _ := json.Marshal(result)

    fmt.Println(string(out))

}```


查看完整回答
反對 回復 2023-08-14
  • 1 回答
  • 0 關注
  • 199 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號