I have a small script I'm testing to pull json information out of graphite. When I dump the http.Get.body response into a var its in bytes as it should be, and the json.Unmarshal happens properly with a pointer to my struct, but when I try to print out the data in my struct the struct has no information in it, and I'm confused as to why. Any help would be appreciated.
评论:
jerf:
Dangle76:To get useful help, you'll need to put the JSON response into the code as well. I suggest using the Go playground to post the request; it makes it very easy to support people in situations like this. If you include it in the post and decode from the []byte, it'll probably be easy to answer. As it stands now, the best thing I can give you is "Your struct probably doesn't match the JSON you're getting back."
jerf:Unfortunately the server is closed to the outside :\ and my admin is gone so I can't open it to do that. The response stored in res is a giant byte array. Unless I'm missing something, I thought the bytes fed to json.Unmarshal were decoded when stored in the pointer to the struct?
this is a sample response via curl however:
[ { "target": "carbon.agents.metricman-a.procs", "datapoints": [ [ 245, 1516310940 ], [ 245, 1516311000 ] ] } ]
Dangle76:That sample is enough to see the problem. You're trying to decode an object, but what you have is an array. I believe if you change stuff to be
[]data{}
instead, it'll decode into a slice with onedata
element for you.I wasn't asking you to open the endpoint; I was asking for a sample []byte embedded in a go playground instance so we could see a sample of the source data, which is what turned out to be necessary to identify the problem, since the code looked correct.
If you know your datapoints are ints, I'd recommend setting them to
[][]int
or something as well; you're going to get tired of the casting frominterface{}
.
vagmi:Possibly, at times they can be null so setting it as a slice of int could throw an error couldn't it? I used some null examples when I used the json to go converter tool
Changing it a slice of the struct worked perfectly. I didn't even think about the array brackets around the json object thanks!
ChurroLoco:
json.Unmarshal
returns an error. You might want to check that. I think the[][]interface{}
might be the issue. I would recommend that you unmarshal it as a[]interface{}
. Subsequently, you can access each of theseDatapoints
' value perform a type assertion on concrete array of some type.
You should catch and check the error returned.
Also it looks like the JSON is an array of objects that match you ‘data’ data type, but you are trying to marshal it into a single object. Change your local ‘stuff’ variable to be of type []data.
var stuff []data or stuff := []data{}
