Parse JSON in Go

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

Parse JSON in Go

问题

这是调用 AWS S3 的 'ListObjects' 时的 JSON 输出示例:

{
    "Contents": [{
        "ETag": "9e2bc2894b23742b7bb688c646c6fee9",
        "Key": "DSC-0237.jpg",
        "LastModified": "2017-09-06 21:53:15 +0000 UTC",
        "Owner": {
            "DisplayName": "demo-user",
            "ID": "a9e2f170a6880f1d61852df8e523e88ca2a2b7abd093476cc93f1239ab5063c6"
        },
        "Size": 117904,
        "StorageClass": "STANDARD"
    }, {
        "ETag": "\"9e2bc2894b23742b7bb688c646c6fee9\"",
        "Key": "DSC-0238.jpg",
        "LastModified": "2017-09-06 21:52:24 +0000 UTC",
        "Owner": {
            "DisplayName": "demo-user",
            "ID": "a9e2f170a6880f1d61852df8e523e88ca2a2b7abd093476cc93f1239ab5063c6"
        },
        "Size": 117904,
        "StorageClass": "STANDARD"
    }, {
        "ETag": "\"9e2bc2894b23742b7bb688c646c6fee9\"",
        "Key": "DSC-0239.jpg",
        "LastModified": "2017-09-06 21:53:01 +0000 UTC",
        "Owner": {
            "DisplayName": "demo-user",
            "ID": "a9e2f170a6880f1d61852df8e523e88ca2a2b7abd093476cc93f1239ab5063c6"
        },
        "Size": 117904,
        "StorageClass": "STANDARD"
    }],
    "IsTruncated": false,
    "Marker": "",
    "MaxKeys": 5,
    "Name": "test-bucket-x011pp3",
    "Prefix": ""
}

我如何在 Go 中解析这个 JSON?我主要想收集以下信息:

  • 存储桶名称(Bucket Name)
  • 键(Key)
  • 大小(Size)
  • 拥有者的显示名称(Owner's DisplayName)
  • 最后修改时间(LastModified)

我之前使用 Python,用 Python 来解析非常简单,像这样:

import json

json_result = json.loads(json_string)
bucket_name = json_result['Name']
for idx, obj in enumerate(json_result['Contents']):
    key = obj['Key']
    size = obj['Size']
    lastmod = obj['LastModified']
    owner = obj['Owner']['DisplayName']

谢谢帮助!

英文:

This is an example of JSON output when calling 'ListObjects' for AWS S3

{
    "Contents": [{
        "ETag": "9e2bc2894b23742b7bb688c646c6fee9",
        "Key": "DSC-0237.jpg",
        "LastModified": "2017-09-06 21:53:15 +0000 UTC",
        "Owner": {
            "DisplayName": "demo-user",
            "ID": "a9e2f170a6880f1d61852df8e523e88ca2a2b7abd093476cc93f1239ab5063c6"
        },
        "Size": 117904,
        "StorageClass": "STANDARD"
    }, {
        "ETag": "\"9e2bc2894b23742b7bb688c646c6fee9\"",
        "Key": "DSC-0238.jpg",
        "LastModified": "2017-09-06 21:52:24 +0000 UTC",
        "Owner": {
            "DisplayName": "demo-user",
            "ID": "a9e2f170a6880f1d61852df8e523e88ca2a2b7abd093476cc93f1239ab5063c6"
        },
        "Size": 117904,
        "StorageClass": "STANDARD"
    }, {
        "ETag": "\"9e2bc2894b23742b7bb688c646c6fee9\"",
        "Key": "DSC-0239.jpg",
        "LastModified": "2017-09-06 21:53:01 +0000 UTC",
        "Owner": {
            "DisplayName": "demo-user",
            "ID": "a9e2f170a6880f1d61852df8e523e88ca2a2b7abd093476cc93f1239ab5063c6"
        },
        "Size": 117904,
        "StorageClass": "STANDARD"
    }],
    "IsTruncated": false,
    "Marker": "",
    "MaxKeys": 5,
    "Name": "test-bucket-x011pp3",
    "Prefix": ""
}

How do I parse this in Go? Chiefly I am interested in collecting:

  • Bucket Name
  • Key
  • Size
  • Owner's DisplayName
  • LastModified

I am coming from Python and in Python it would be something really simple like:

json_result = json.loads(json_string)
bucket_name = json_result['Name']
for idx, obj in enumerate(json_result['Contents']):
    key = obj['Key']
    size = obj['Size']
    lastmod = obj['LastModified']
    owner= obj['Owner']['DisplayName']

Thank you for the help!

答案1

得分: 1

这是一个类似于这样的代码:

package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"log"
)

var jsonData = []byte(`
{
    "Contents": [{
        "ETag": "9e2bc2894b23742b7bb688c646c6fee9",
        "Key": "DSC-0237.jpg",
        "LastModified": "2017-09-06 21:53:15 +0000 UTC",
        "Owner": {
            "DisplayName": "demo-user",
            "ID": "a9e2f170a6880f1d61852df8e523e88ca2a2b7abd093476cc93f1239ab5063c6"
        },
        "Size": 117904,
        "StorageClass": "STANDARD"
    }, {
        "ETag": "\"9e2bc2894b23742b7bb688c646c6fee9\"",
        "Key": "DSC-0238.jpg",
        "LastModified": "2017-09-06 21:52:24 +0000 UTC",
        "Owner": {
            "DisplayName": "demo-user",
            "ID": "a9e2f170a6880f1d61852df8e523e88ca2a2b7abd093476cc93f1239ab5063c6"
        },
        "Size": 117904,
        "StorageClass": "STANDARD"
    }, {
        "ETag": "\"9e2bc2894b23742b7bb688c646c6fee9\"",
        "Key": "DSC-0239.jpg",
        "LastModified": "2017-09-06 21:53:01 +0000 UTC",
        "Owner": {
            "DisplayName": "demo-user",
            "ID": "a9e2f170a6880f1d61852df8e523e88ca2a2b7abd093476cc93f1239ab5063c6"
        },
        "Size": 117904,
        "StorageClass": "STANDARD"
    }],
    "IsTruncated": false,
    "Marker": "",
    "MaxKeys": 5,
    "Name": "test-bucket-x011pp3",
    "Prefix": ""
}`)

type Response struct {
	Contents    []*Content
	IsTruncated bool
	Marker      string
	MaxKeys     int
	Name        string
	Prefix      string
}

type Content struct {
	ETag         string
	Key          string
	LastModified string
	Owner        *Owner
	Size         int
	StroageClass string
}

type Owner struct {
	DisplayName string
	ID          string
}

func main() {
	resp := &Response{}

	if err := json.NewDecoder(bytes.NewBuffer(jsonData)).Decode(resp); err != nil {
		log.Fatal(err)
	}

	fmt.Printf("%#v", resp)
}

Go Playground中尝试一下。

你也可以阅读这个链接:https://golang.org/pkg/encoding/json/

英文:

It is something like this

package main
import (
"bytes"
"encoding/json"
"fmt"
"log"
)
var jsonData = []byte(`
{
"Contents": [{
"ETag": "9e2bc2894b23742b7bb688c646c6fee9",
"Key": "DSC-0237.jpg",
"LastModified": "2017-09-06 21:53:15 +0000 UTC",
"Owner": {
"DisplayName": "demo-user",
"ID": "a9e2f170a6880f1d61852df8e523e88ca2a2b7abd093476cc93f1239ab5063c6"
},
"Size": 117904,
"StorageClass": "STANDARD"
}, {
"ETag": "\"9e2bc2894b23742b7bb688c646c6fee9\"",
"Key": "DSC-0238.jpg",
"LastModified": "2017-09-06 21:52:24 +0000 UTC",
"Owner": {
"DisplayName": "demo-user",
"ID": "a9e2f170a6880f1d61852df8e523e88ca2a2b7abd093476cc93f1239ab5063c6"
},
"Size": 117904,
"StorageClass": "STANDARD"
}, {
"ETag": "\"9e2bc2894b23742b7bb688c646c6fee9\"",
"Key": "DSC-0239.jpg",
"LastModified": "2017-09-06 21:53:01 +0000 UTC",
"Owner": {
"DisplayName": "demo-user",
"ID": "a9e2f170a6880f1d61852df8e523e88ca2a2b7abd093476cc93f1239ab5063c6"
},
"Size": 117904,
"StorageClass": "STANDARD"
}],
"IsTruncated": false,
"Marker": "",
"MaxKeys": 5,
"Name": "test-bucket-x011pp3",
"Prefix": ""
}`,
)
type Response struct {
Contents    []*Content
IsTruncated bool
Marker      string
MaxKeys     int
Name        string
Prefix      string
}
type Content struct {
ETag         string
Key          string
LastModified string
Owner        *Owner
Size         int
StroageClass string
}
type Owner struct {
DisplayName string
ID          string
}
func main() {
resp := &Response{}
if err := json.NewDecoder(bytes.NewBuffer(jsonData)).Decode(resp); err != nil {
log.Fatal(err)
}
fmt.Printf("%#v", resp)
}

Try it in the Go Playground

And you should read this https://golang.org/pkg/encoding/json/

答案2

得分: 1

请参考 https://golang.org/pkg/encoding/json

你可以使用 JSON 字段来注释一个结构体,以便从 JSON 缓冲区中解组,类似于以下示例:

type AWSObject struct {
    Size  int            `json:"Size"`
    Key   string         `json:"key"`
    Owner AWSObjectOwner `json:"Owner"`
}

type AWSObjectOwner struct {
    DisplayName string `json:"DisplayName"`
}

var awsObjects []AWSObject
err := json.Unmarshal(jsonBuffer, &awsObjects)
if err != nil {
    fmt.Printf("Error unmarshaling objects: " + err.Error() + "\n")
    // ...
}
英文:

See https://golang.org/pkg/encoding/json

You annotate a struct with JSON fields that should be unmarshalled from the buffer of JSON, something like this:

type AWSObject struct {
Size  int            `json:"Size"`
Key   string         `json:"key"`
Owner AWSObjectOwner `json:"Owner"`
}
type AWSObjectOwner struct {
DisplayName          `json:"DisplayName"`
}
var awsObjects []AWSObject
err = json.Unmarshal(jsonBuffer, &awsObjects)
if err != nil {
fmt.Printf("Error unmarshaling objects: " + err.Error() + "\n")
...
}

答案3

得分: 1

使用quicktype生成了您的模型、编组代码和使用说明:

// 要解析此JSON数据,请将以下代码添加到您的项目中:
//
//    r, err := UnmarshalListObjectsResponse(bytes)
//    bytes, err = r.Marshal()

package main

import "encoding/json"

func UnmarshalListObjectsResponse(data []byte) (ListObjectsResponse, error) {
    var r ListObjectsResponse
    err := json.Unmarshal(data, &r)
    return r, err
}

func (r *ListObjectsResponse) Marshal() ([]byte, error) {
    return json.Marshal(r)
}

type ListObjectsResponse struct {
    Contents    []Content `json:"Contents"`
    IsTruncated bool      `json:"IsTruncated"`
    Marker      string    `json:"Marker"`
    MaxKeys     int64     `json:"MaxKeys"`
    Name        string    `json:"Name"`
    Prefix      string    `json:"Prefix"`
}

type Content struct {
    ETag         string `json:"ETag"`
    Key          string `json:"Key"`
    LastModified string `json:"LastModified"`
    Owner        Owner  `json:"Owner"`
    Size         int64  `json:"Size"`
    StorageClass string `json:"StorageClass"`
}

type Owner struct {
    DisplayName string `json:"DisplayName"`
    ID          string `json:"ID"`
}

正如其他人建议的那样,最好使用AWS SDK for Go,但是这种方法在下次需要解析任意JSON时可能会有用。

英文:

Using quicktype, I generated your model, marshaling code, and usage instructions:

<!-- language: go -->

// To parse this JSON data, add this code to your project and do:
//
//    r, err := UnmarshalListObjectsResponse(bytes)
//    bytes, err = r.Marshal()
package main
import &quot;encoding/json&quot;
func UnmarshalListObjectsResponse(data []byte) (ListObjectsResponse, error) {
var r ListObjectsResponse
err := json.Unmarshal(data, &amp;r)
return r, err
}
func (r *ListObjectsResponse) Marshal() ([]byte, error) {
return json.Marshal(r)
}
type ListObjectsResponse struct {
Contents    []Content `json:&quot;Contents&quot;`
IsTruncated bool      `json:&quot;IsTruncated&quot;`
Marker      string    `json:&quot;Marker&quot;`
MaxKeys     int64     `json:&quot;MaxKeys&quot;`
Name        string    `json:&quot;Name&quot;`
Prefix      string    `json:&quot;Prefix&quot;`
}
type Content struct {
ETag         string `json:&quot;ETag&quot;`
Key          string `json:&quot;Key&quot;`
LastModified string `json:&quot;LastModified&quot;`
Owner        Owner  `json:&quot;Owner&quot;`
Size         int64  `json:&quot;Size&quot;`
StorageClass string `json:&quot;StorageClass&quot;`
}
type Owner struct {
DisplayName string `json:&quot;DisplayName&quot;`
ID          string `json:&quot;ID&quot;`
}

As others suggested, it's probably best to use the AWS SDK for Go, but this method may be useful in general the next time you need to parse arbitrary JSON.

huangapple
  • 本文由 发表于 2017年9月7日 06:49:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/46085404.html
匿名

发表评论

匿名网友

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

确定