How to parse the json array in golang?

前端 未结 1 584
猫巷女王i
猫巷女王i 2020-12-20 05:50
package main

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

type PublicKey struct {
    name string
    price string
}

type KeysResponse struct {
    Collection []P         


        
相关标签:
1条回答
  • 2020-12-20 06:30

    You missed one point only: you need to export the fields of your struct:

    type PublicKey struct {
        Name  string
        Price string
    }
    

    And it will work (try it on the Go Playground):

    [{Name:Galaxy Nexus Price:3460.00} {Name:Galaxy Nexus Price:3460.00}]
    

    Note that the JSON text contains the field names with lowercased text, but the json package is "clever" enough to match them. If they would be completely different, you could use struct tags to tell the json package how they are found (or how they should be marshaled) in the JSON text, e.g.:

    type PublicKey struct {
        Name  string `json:"some_name"`
        Price string `json:"JsonPrice"`
    }
    

    To parse your other JSON text, create a Go struct that models the JSON data. I suggest to format the JSON to see the real structure, e.g. you can use this online JSON formatter/validator. Then you can unmarshal into a slice of this struct.

    Or simply unmarshal into a slice of maps, e.g. []map[string]interface{}, but then you need to index the map to get the different values, and you also need to use type assertion to get "typed" values.

    0 讨论(0)
提交回复
热议问题