J'essaie de prendre les données dans le fichier "carrier.json" et de créer un fichier CSV en utilisant Go avec les informations. Cependant, je reçois l'erreur de suivi/avisVous cherchez à convertir un fichier json dans un fichier csv en utilisant Golang
./carrier_json.go:53:48: obj.APIVersion undefined (type Json has no field or method APIVersion)
./carrier_json.go:53:69: obj.CarrierSid undefined (type Json has no field or method CarrierSid)
./carrier_json.go:53:85: obj.AccountSid undefined (type Json has no field or method AccountSid)
./carrierlookup.go:12:6: main redeclared in this block
previous declaration at ./carrier_json.go:31:6
J'ai cherché en ligne pendant plusieurs heures et toute aide serait appréciée. Remarque, je ne suis pas très technique.
Le "carrier.json" a ce qui suit,
{
"Message360": {
"ResponseStatus": 1,
"Carrier": {
"ApiVersion": "3",
"CarrierSid": "c7e57a2a-92d7-0430",
"AccountSid": "2f4ce81a-f08d-04e1",
"PhoneNumber": "+19499999999",
"Network": "Cellco Partnership dba Verizon Wireless - CA",
"Wireless": "true",
"ZipCode": "92604",
"City": "Irvine",
"Price": "0.0003",
"Status": "success",
"DateCreated": "2017-10-13 18:44:32"
}
}
}
J'ai un fichier appelé go carrier_json.go qui a les informations suivantes.
package main
import (
"encoding/csv"
"encoding/json"
"fmt"
"io/ioutil"
"os"
"strconv"
)
type Json struct {
Message360 struct {
ResponseStatus int `json:"ResponseStatus"`
Carrier struct {
APIVersion string `json:"ApiVersion"`
CarrierSid string `json:"CarrierSid"`
AccountSid string `json:"AccountSid"`
PhoneNumber string `json:"PhoneNumber"`
Network string `json:"Network"`
Wireless string `json:"Wireless"`
ZipCode string `json:"ZipCode"`
City string `json:"City"`
Price string `json:"Price"`
Status string `json:"Status"`
DateCreated string `json:"DateCreated"`
} `json:"Carrier"`
} `json:"Message360"`
}
func main() {
// reading data from JSON File
data, err := ioutil.ReadFile("carrier.json")
if err != nil {
fmt.Println(err)
}
// Unmarshal JSON data
var d []Json
err = json.Unmarshal([]byte(data), &d)
if err != nil {
fmt.Println(err)
}
// Create a csv file
f, err := os.Create("./carrier.csv")
if err != nil {
fmt.Println(err)
}
defer f.Close()
// Write Unmarshaled json data to CSV file
w := csv.NewWriter(f)
for _, obj := range d {
var record []string
record = append(record, strconv.FormatInt(obj.APIVersion, 10), obj.CarrierSid, obj.AccountSid)
w.Write(record)
record = nil
}
w.Flush()
}
Le message d'erreur est très clair. le type 'Json' n'a qu'un seul champ nommé' Message360'. Pour accéder par exemple. 'APIVersion' vous devez accéder à' jsonObj.Message360.APIVersio'n (à condition que 'jsonObj' soit de type' JSON'). – PieOhPah