第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問題,去搜搜看,總會(huì)有你想問的

正確的 json 取消在 Go 中使用空接口進(jìn)行取消編組

正確的 json 取消在 Go 中使用空接口進(jìn)行取消編組

Go
繁星coding 2022-09-12 20:23:56
我目前正在學(xué)習(xí)golang,(可能和我之前的許多其他人一樣)我試圖正確理解空界面。作為一個(gè)練習(xí),我正在閱讀Postman生成的一個(gè)大json文件,并試圖只訪問一個(gè)字段(在眾多可用的字段中)。以下是json的簡單表示形式,沒有我不想閱讀的不必要的字段(但仍然存在):{    "results": [        {            "times": [                1,                2,                3,                4                ]        }    ]}由于 json 對(duì)象很大,我選擇不使用自定義結(jié)構(gòu)取消封接,而是決定使用空接口interface{}一段時(shí)間后,我設(shè)法得到了一些工作代碼,但我非常確定這不是正確的方法。byteValue, _ := ioutil.ReadAll(jsonFile)var result map[string]interface{}err = json.Unmarshal(byteValue, &result)if err != nil {    log.Fatalln(err)}// ESPECIALLY UGLYr := result["results"].([]interface{})r1 := r[0].(map[string]interface{})r2 := r1["times"].([]interface{})times := make([]float64, len(r2))for i := range r2 {    times[i] = r2[i].(float64)}有沒有更好的方法來瀏覽我的json對(duì)象,而不必每次我越來越深入到對(duì)象時(shí)實(shí)例化新變量?
查看完整描述

2 回答

?
翻閱古今

TA貢獻(xiàn)1780條經(jīng)驗(yàn) 獲得超5個(gè)贊

  1. 即使 JSON 很大,您也只需定義您實(shí)際關(guān)心的字段

  2. 僅當(dāng)密鑰不是有效的 Go 標(biāo)識(shí)符(在本例中為密鑰是標(biāo)識(shí))時(shí),才需要使用 JSON 標(biāo)記,即使這樣,有時(shí)也可以使用map[string]something

  3. 除非您需要子s用于某些功能或其他功能,否則您不需要定義它們struct

  4. 除非您需要重用該類型,否則您甚至不必定義它,您只需在聲明時(shí)定義結(jié)構(gòu)即可

例:

package main


import (

   "encoding/json"

   "fmt"

)


const s = `

{

   "results": [

      {

         "times": [1, 2, 3, 4]

      }

   ]

}

`


func main() {

   var t struct {

      Results []struct {

         Times []int

      }

   }

   json.Unmarshal([]byte(s), &t)

   fmt.Printf("%+v\n", t) // {Results:[{Times:[1 2 3 4]}]}

}


查看完整回答
反對(duì) 回復(fù) 2022-09-12
?
拉風(fēng)的咖菲貓

TA貢獻(xiàn)1995條經(jīng)驗(yàn) 獲得超2個(gè)贊

[...]嘗試僅訪問一個(gè)字段(在眾多可用字段中)。

對(duì)于這個(gè)具體的用例,我將使用一個(gè)庫來查詢和訪問已知路徑中的單個(gè)值,例如:

https://github.com/jmespath/go-jmespath

另一方面,如果您正在練習(xí)如何訪問JSON中的嵌套值,我建議您嘗試編寫一個(gè)遞歸函數(shù),該函數(shù)以與go-jmespath相同(但簡單)的方式遵循未知結(jié)構(gòu)中的路徑。

好吧,我挑戰(zhàn)了自己,花了一個(gè)小時(shí)寫這篇文章。它的工作原理。不確定性能或錯(cuò)誤,它真的很有限:)

https://play.golang.org/p/dlIsmG6Lk-p

package main


import (

    "encoding/json"

    "errors"

    "fmt"

    "strings"

)


func main() {


    // I Just added a bit more of data to the structure to be able to test different paths

    fileContent := []byte(`

    {"results": [

            {"times": [

                    1,

                    2,

                    3,

                    4

        ]},

        {"times2": [

                    5,

                    6,

                    7,

                    8

        ]},

        {"username": "rosadabril"},

        {"age": 42},

        {"location": [41.5933262, 1.8376757]}

        

    ],

    "more_results": {

        "nested_1": {

            "nested_2":{

                "foo": "bar"

            }

        }

    }

    }`)


    var content map[string]interface{}

    if err := json.Unmarshal(fileContent, &content); err != nil {

        panic(err)

    }


    // some paths to test

    valuePaths := []string{

        "results.times",

        "results.times2",

        "results.username",

        "results.age",

        "results.doesnotexist",

        "more_results.nested_1.nested_2.foo",

    }


    for _, p := range valuePaths {

        breadcrumbs := strings.Split(p, ".")


        value, err := search(breadcrumbs, content)

        if err != nil {

            fmt.Printf("\nerror searching '%s': %s\n", p, err)

            continue

        }


        fmt.Printf("\nFOUND A VALUE IN: %s\n", p)

        fmt.Printf("Type: %T\nValue: %#v\n", value, value)

    }


}


// search is our fantastic recursive function! The idea is to search in the structure in a very basic way, for complex querying use jmespath

func search(breadcrumbs []string, content map[string]interface{}) (interface{}, error) {

    // we should never hit this point, but better safe than sorry and we could incurr in an out of range error (check line 82)

    if len(breadcrumbs) == 0 {

        return nil, errors.New("ran out of breadcrumbs :'(")

    }


    // flag that indicates if we are at the end of our trip and whe should return the value without more checks

    lastBreadcrumb := len(breadcrumbs) == 1


    // current breadcrumb is always the first element.

    currentBreadcrumb := breadcrumbs[0]


    if value, found := content[currentBreadcrumb]; found {

        if lastBreadcrumb {

            return value, nil

        }

        // if the value is a map[string]interface{}, go down the rabbit hole, recursion!

        if aMap, isAMap := value.(map[string]interface{}); isAMap {

            // we are calling ourselves popping the first breadcrumb and passing the current map

            return search(breadcrumbs[1:], aMap)

        }

        // if it's an array of interfaces the thing gets complicated :(

        if anArray, isArray := value.([]interface{}); isArray {

            for _, something := range anArray {

                if aMap, isAMap := something.(map[string]interface{}); isAMap && len(breadcrumbs) > 1 {

                    if v, err := search(breadcrumbs[1:], aMap); err == nil {

                        return v, nil

                    }

                }

            }

        }

    }

    return nil, errors.New("woops, nothing here")

}


查看完整回答
反對(duì) 回復(fù) 2022-09-12
  • 2 回答
  • 0 關(guān)注
  • 107 瀏覽

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)