英文:
Parsing json file in golang
问题
我有一个像这样的 JSON 结构:
{  
    "some text":[  
        {  
            "sha":"1234567",
            "message":"hello world",
            "author":"varung",
            "timestamp":1479445228
        }
    ]
}
我需要使用 Golang 访问 sha 的值。我该如何做?
英文:
I have a json structure like this
{  
"some text":[  
  {  
     "sha":"1234567",
     "message":"hello world",
     "author":"varung",
     "timestamp":1479445228
  }
]
}
I need to access the value of sha, using golang. How can I do it?
答案1
得分: 2
你可以很容易地使用Go语言的encoding/json包。以下是下面代码的playground链接。
package main
import (
	"encoding/json"
	"fmt"
	"log"
)
var a = `{
	"sometext": [
		{
			"sha": "1234567",
			"message": "hello world",
			"author": "varung",
			"timestamp": 1479445228
		}
	]
}`
type Root struct {
	Text []*Object `json:"sometext"`
}
type Object struct {
	Sha       string `json:"sha"`
	Message   string `json:"message"`
	Author    string `json:"author"`
	Timestamp int    `json:"timestamp"`
}
func main() {
	var j Root
	err := json.Unmarshal([]byte(a), &j)
	if err != nil {
		log.Fatalf("error parsing JSON: %s\n", err.Error())
	}
	fmt.Printf("%+v\n", j.Text[0].Sha)
}
以上是代码的翻译部分。
英文:
You can use Go's encoding/json package quite easily. Here is a playground link to the code below.
package main
import (
	"encoding/json"
	"fmt"
	"log"
)
var a = `{  
"sometext":[  
  {  
     "sha":"1234567",
     "message":"hello world",
     "author":"varung",
     "timestamp":1479445228
  }
]
}`
type Root struct {
	Text []*Object `json:"sometext"`
}
type Object struct {
	Sha       string `json:"sha"`
	Message   string `json:"message"`
	Author    string `json:"author"`
	Timestamp int    `json:"timestamp"`
}
func main() {
	var j Root
	err := json.Unmarshal([]byte(a), &j)
	if err != nil {
		log.Fatalf("error parsing JSON: %s\n", err.Error())
	}
	fmt.Printf("%+v\n", j.Text[0].Sha)
}
答案2
得分: 0
我不知道除了解析JSON之外还有其他的方法。
import (
    "time"
    "fmt"
    "encoding/json"
)
type MyObj struct {
    Sha       string    `json:"sha"`
    Message   string    `json:"message"`
    Author    string    `json:"author"`
    Timestamp time.Time `json:"timestamp"`
}
type MyObjs struct {
    Objs []MyObj `json:"some text"`
}
func PrintSha(json []byte) {
    var myObjs MyObjs
    if err := json.Unmarshal(json, &myObjs); err != nil {
        panic(err)
    }
    myObj := myObjs.Objs[0]
    fmt.Println(myObj.Sha)
}
以上是代码的翻译。
英文:
I don't know of any way other than unmarshaling the json.
import (
        "time"
        "fmt"
        "encoding/json"
)
type MyObj struct {
  Sha string `json:"sha"`
  Message string `json:"message"`
  Author string `json:"author"`
  Timestamp time.Time `json:"timestamp"`
}
type MyObjs struct {
  Objs []MyObj `json:"some text"`
} 
func PrintSha(json []byte) {
  var myObjs MyObjs
  if err := json.Unmarshal(json, &myObjs); err != nil {
    panic(err)
  }
  myObj := myObjs[0]
  fmt.Println(myObj.sha)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论