将json文件从GO服务器提供给javascript客户端

I have a go server which has to respond to a javascript request by serving a json file. The json file is an 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 I do that I get the JSON object in JavaScript, but if I try to look into the JSON to get the array- i.e. console.log(ev.detail.response['trial-data']) then this doesn't work.

ev.detail.response is just a string response, it is not a parsed json object.

First you need to parse it using JSON.parse() and then you can access its content.

See this Javascript example:

var json = '{"trial-data":[{"trial":{"index": 0}},{"trial":{"index":1}}]}'

alert(JSON.parse(json)['trial-data'])

To access the value of the first "index" field, for example:

var idx0 = JSON.parse(json)['trial-data'][0]['trial']['index']