我正在使用GoLang並希望讀取該文件並能夠將每個json對象發送到REST端點。Golang讀取一個Json對象數組
REST端點放在一邊,我解析文件時出現問題。
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"bytes"
"os"
)
func main() {
type myjson struct {
myobjects []struct {
data map[string]string
}
}
file, e := ioutil.ReadFile("dat_one_extract.json")
if e != nil {
fmt.Printf("File Error: [%v]\n", e)
os.Exit(1)
}
dec := json.NewDecoder(bytes.NewReader(file))
var d myjson
dec.Decode(&d)
}
我的JSON文件看起來是這樣的:
[{
"NAME1": "Y",
"NAME2": 1729.0,
"NAME3": "Y",
"NAME4": [
{
"Contact Zip": "33619",
"Date of Contact": "01/21/2015"
}
],
"NAME6": "123456789",
"NAME7": "Walmart",
"NAME8": [
{
"State": "xx",
"Zip Code": "12345",
"Address": "12345 main street",
"Type": "MAILING",
"City": "MyTown"
},
{
"State": "xx",
"Zip Code": "12345",
"Address": "12345 main street",
"Type": "MAILING",
"City": "MyTown"
},
{
"State": "xx",
"Zip Code": "12345",
"Address": "12345 main street",
"Type": "MAILING",
"City": "MyTown"
}
],
"NAME11": "XXXXXXX",
"NAME12": "11/21/2014 14:01:47",
"NAME13": "11/15/2014",
"NAME14": "11/16/1992"
},{
"NAME1": "Y",
"NAME2": 1729.0,
"NAME3": "Y",
"NAME4": [
{
"Contact Zip": "33619",
"Date of Contact": "01/21/2015"
}
],
"NAME6": "123456789",
"NAME7": "Walmart",
"NAME8": [
{
"State": "xx",
"Zip Code": "12345",
"Address": "12345 main street",
"Type": "MAILING",
"City": "MyTown"
},
{
"State": "xx",
"Zip Code": "12345",
"Address": "12345 main street",
"Type": "MAILING",
"City": "MyTown"
},
{
"State": "xx",
"Zip Code": "12345",
"Address": "12345 main street",
"Type": "MAILING",
"City": "MyTown"
}
],
"NAME11": "XXXXXXX",
"NAME12": "11/21/2014 14:01:47",
"NAME13": "11/15/2014",
"NAME14": "11/16/1992"
}]
我缺少訪問每個數組元素,並把它傳遞到終點? 我不想處理元素,只需將json對象一次發送到端點1即可。
先謝謝您,併爲作爲golang noob的道歉!
的[我的結構沒有編組爲JSON]可能重複(http://stackoverflow.com/questions/15452004/my-structures-are-not-marshalling-into-json) – 2015-04-06 00:32:08
**決不* *忽略錯誤(例如來自'Decode')。 – 2015-04-06 03:12:35