arrays - Serve json file from GO server to javascript client -
i have go server has respond javascript request serving json file. json file array of objects.
my code :
server side
package expt import ( "net/http" ) func init() { http.handlefunc("/", handlestatic) http.handlefunc("/loadtrials", handleloadjson) } func handlestatic(w http.responsewriter, r *http.request) { w.header().set("cache-control", "no-cache") http.servefile(w, r, "static/"+r.url.path) } func handleloadjson(w http.responsewriter, r *http.request) { http.servefile(w, r, "static/trial.json") }
client side
loadtrials : function loadtrials() { var _this = this, load = this.shadowroot.queryselector('#load-trial'); load.url="http://url:8080/loadtrials"; load.go() load.addeventlistener('core-response', function(ev) { console.log(ev.detail.response) }, false); }
json
{ "trial-data" : [ { "trial" : { "index": 0, } }, { "trial" : { "index": 1, } } ] }
if json object in javascript, if try json array- i.e. console.log(ev.detail.response['trial-data']) doesn't work.
ev.detail.response
string response, not parsed json object.
first need parse using json.parse()
, can access content.
see javascript example:
var json = '{"trial-data":[{"trial":{"index": 0}},{"trial":{"index":1}}]}' alert(json.parse(json)['trial-data'])
to access value of first "index"
field, example:
var idx0 = json.parse(json)['trial-data'][0]['trial']['index']
Comments
Post a Comment