How to parse the json array in golang?

huangapple go评论86阅读模式
英文:

How to parse the json array in golang?

问题

package main

import (
	"encoding/json"
	"fmt"
)

type PublicKey struct {
	Name  string `json:"name"`
	Price string `json:"price"`
}

type KeysResponse struct {
	Collection []PublicKey `json:"collection"`
}

func main() {
	s := `[{"name":"Galaxy Nexus", "price":"3460.00"},{"name":"Galaxy Nexus", "price":"3460.00"}]`

	keys := make([]PublicKey, 0)
	err := json.Unmarshal([]byte(s), &keys)
	if err == nil {
		fmt.Printf("%+v\n", keys)
	} else {
		fmt.Println(err)
		fmt.Printf("%+v\n", keys)
	}
}
英文:
package main

import (
    "encoding/json"
    "fmt"
)

type PublicKey struct {
    name string
    price string
}

type KeysResponse struct {
    Collection []PublicKey
}

func main() {
    s := `[{"name":"Galaxy Nexus", "price":"3460.00"},{"name":"Galaxy Nexus", "price":"3460.00"}]`
    
    keys := make([]PublicKey,0)
    err := json.Unmarshal([]byte(s), &keys)
    if err == nil {
        fmt.Printf("%+v\n", keys)
    } else {
        fmt.Println(err)
        fmt.Printf("%+v\n", keys)
    }
}

OutPut: [{name: price:}]

I have api call returned result it is like array of object (json array) complex format. I need to parse that result by golang how can I achieve? Following data is my result it is get from api call.

[{"id":694476444991229955,"id_str":"694476444991229955","text":"Got it","sender":{"id":1690262984,"id_str":"1690262984","name":"Ashok Kumar T","screen_name":"Ashok_kumar_T","location":"Trivandrum","description":"","url":null,"entities":{"description":{"urls":[]}},"protected":false,"followers_count":68,"friends_count":32,"listed_count":0,"created_at":"Thu Aug 22 06:52:53 +0000 2013","favourites_count":5,"utc_offset":19800,"time_zone":"Chennai","geo_enabled":true,"verified":false,"statuses_count":124,"lang":"en","contributors_enabled":false,"is_translator":false,"is_translation_enabled":false,"profile_background_color":"131516","profile_background_image_url":"http:\/\/abs.twimg.com\/images\/themes\/theme14\/bg.gif","profile_background_image_url_https":"https:\/\/abs.twimg.com\/images\/themes\/theme14\/bg.gif","profile_background_tile":true,"profile_image_url":"http:\/\/pbs.twimg.com\/profile_images\/378800000337984382\/5eded5a0c6fda4a85511aff15e5befd9_normal.jpeg","profile_image_url_https":"https:\/\/pbs.twimg.com\/profile_images\/378800000337984382\/5eded5a0c6fda4a85511aff15e5befd9_normal.jpeg","profile_banner_url":"https:\/\/pbs.twimg.com\/profile_banners\/1690262984\/1429709252","profile_link_color":"009999","profile_sidebar_border_color":"EEEEEE","profile_sidebar_fill_color":"EFEFEF","profile_text_color":"333333","profile_use_background_image":true,"has_extended_profile":false,"default_profile":false,"default_profile_image":false,"following":true,"follow_request_sent":false,"notifications":false},"sender_id":1690262984,"sender_id_str":"1690262984","sender_screen_name":"Ashok_kumar_T","recipient":{"id":4848598394,"id_str":"4848598394","name":"Prabhu","screen_name":"prabhu_cfml","location":"","description":"","url":null,"entities":{"description":{"urls":[]}},"protected":false,"followers_count":1,"friends_count":1,"listed_count":0,"created_at":"Tue Feb 02 09:25:17 +0000 2016","favourites_count":0,"utc_offset":null,"time_zone":null,"geo_enabled":false,"verified":false,"statuses_count":0,"lang":"en-gb","contributors_enabled":false,"is_translator":false,"is_translation_enabled":false,"profile_background_color":"F5F8FA","profile_background_image_url":null,"profile_background_image_url_https":null,"profile_background_tile":false,"profile_image_url":"http:\/\/abs.twimg.com\/sticky\/default_profile_images\/default_profile_3_normal.png","profile_image_url_https":"https:\/\/abs.twimg.com\/sticky\/default_profile_images\/default_profile_3_normal.png","profile_link_color":"2B7BB9","profile_sidebar_border_color":"C0DEED","profile_sidebar_fill_color":"DDEEF6","profile_text_color":"333333","profile_use_background_image":true,"has_extended_profile":false,"default_profile":true,"default_profile_image":true,"following":false,"follow_request_sent":false,"notifications":false},"recipient_id":4848598394,"recipient_id_str":"4848598394","recipient_screen_name":"prabhu_cfml","created_at":"Tue Feb 02 11:04:21 +0000 2016","entities":{"hashtags":[],"symbols":[],"user_mentions":[],"urls":[]}},{"id":694476425793916931,"id_str":"694476425793916931","text":"Hi","sender":{"id":1690262984,"id_str":"1690262984","name":"Ashok Kumar T","screen_name":"Ashok_kumar_T","location":"Trivandrum","description":"","url":null,"entities":{"description":{"urls":[]}},"protected":false,"followers_count":68,"friends_count":32,"listed_count":0,"created_at":"Thu Aug 22 06:52:53 +0000 2013","favourites_count":5,"utc_offset":19800,"time_zone":"Chennai","geo_enabled":true,"verified":false,"statuses_count":124,"lang":"en","contributors_enabled":false,"is_translator":false,"is_translation_enabled":false,"profile_background_color":"131516","profile_background_image_url":"http:\/\/abs.twimg.com\/images\/themes\/theme14\/bg.gif","profile_background_image_url_https":"https:\/\/abs.twimg.com\/images\/themes\/theme14\/bg.gif","profile_background_tile":true,"profile_image_url":"http:\/\/pbs.twimg.com\/profile_images\/378800000337984382\/5eded5a0c6fda4a85511aff15e5befd9_normal.jpeg","profile_image_url_https":"https:\/\/pbs.twimg.com\/profile_images\/378800000337984382\/5eded5a0c6fda4a85511aff15e5befd9_normal.jpeg","profile_banner_url":"https:\/\/pbs.twimg.com\/profile_banners\/1690262984\/1429709252","profile_link_color":"009999","profile_sidebar_border_color":"EEEEEE","profile_sidebar_fill_color":"EFEFEF","profile_text_color":"333333","profile_use_background_image":true,"has_extended_profile":false,"default_profile":false,"default_profile_image":false,"following":true,"follow_request_sent":false,"notifications":false},"sender_id":1690262984,"sender_id_str":"1690262984","sender_screen_name":"Ashok_kumar_T","recipient":{"id":4848598394,"id_str":"4848598394","name":"Prabhu","screen_name":"prabhu_cfml","location":"","description":"","url":null,"entities":{"description":{"urls":[]}},"protected":false,"followers_count":1,"friends_count":1,"listed_count":0,"created_at":"Tue Feb 02 09:25:17 +0000 2016","favourites_count":0,"utc_offset":null,"time_zone":null,"geo_enabled":false,"verified":false,"statuses_count":0,"lang":"en-gb","contributors_enabled":false,"is_translator":false,"is_translation_enabled":false,"profile_background_color":"F5F8FA","profile_background_image_url":null,"profile_background_image_url_https":null,"profile_background_tile":false,"profile_image_url":"http:\/\/abs.twimg.com\/sticky\/default_profile_images\/default_profile_3_normal.png","profile_image_url_https":"https:\/\/abs.twimg.com\/sticky\/default_profile_images\/default_profile_3_normal.png","profile_link_color":"2B7BB9","profile_sidebar_border_color":"C0DEED","profile_sidebar_fill_color":"DDEEF6","profile_text_color":"333333","profile_use_background_image":true,"has_extended_profile":false,"default_profile":true,"default_profile_image":true,"following":false,"follow_request_sent":false,"notifications":false},"recipient_id":4848598394,"recipient_id_str":"4848598394","recipient_screen_name":"prabhu_cfml","created_at":"Tue Feb 02 11:04:17 +0000 2016","entities":{"hashtags":[],"symbols":[],"user_mentions":[],"urls":[]}}]

答案1

得分: 5

你只错过了一个要点:你需要导出你的结构体字段:

type PublicKey struct {
    Name  string
    Price string
}

然后它就可以工作了(在Go Playground上试一试):

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

请注意,JSON文本中的字段名是小写的,但json包足够“聪明”,可以匹配它们。如果它们完全不同,你可以使用结构体标签告诉json包它们在JSON文本中是如何找到的(或者在JSON文本中如何编组),例如:

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

要解析其他的JSON文本,创建一个Go结构体来模拟JSON数据。我建议格式化JSON以查看实际结构,例如,你可以使用这个在线JSON格式化/验证工具。然后你可以将其解组为该结构体的切片。

或者简单地解组为一个map切片,例如[]map[string]interface{},但是然后你需要通过索引map来获取不同的值,并且还需要使用类型断言来获取“类型化”的值。

英文:

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.

huangapple
  • 本文由 发表于 2016年2月4日 21:57:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/35202961.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定