4

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.

2
  • 4
    Please define "this doesn't work" . What happens? You get JavaScript error? If so, what is it you get? Commented May 14, 2015 at 9:02
  • if i do console.log(ev.detail.response) I get json as string, but if I try to do console.log(ev.detail.response['trial-data']) I got undefined, so it means that ev.detail.response does not return an array Commented May 14, 2015 at 9:14

1 Answer 1

4

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']
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.