1

I'm a little new to JSON Syntax. How can I extract the value of listeners from this JSON array?

http://ws.audioscrobbler.com/2.0/?method=track.getInfo&api_key=31f2cd3c2530c87e110cc5212166d24c&artist=Britney%20Spears&track=If%20U%20Seek%20Amy&format=json

I've tried with myvar.track.listeners but it doesn't work. Can someone point me in the right direction?

The code that I'm using to get that value is:

    function getInfo(artista, titolo) {
artista = artista.replace(" ","%20");
titolo = titolo.replace(" ","%20");
$.post("http://ws.audioscrobbler.com/2.0/?method=track.getInfo&api_key=31f2cd3c2530c87e110cc5212166d24c&artist="+artista+"&track="+titolo+"&format=json", {}, function(data) {
    $("#listeners").html("<span class=\"span_listeners\">Ascoltatori: "+data.track.listeners+"</span>");
}, "json");
}
6
  • 4
    track.listeners is correct, but I'm fairly sure you can't name a variable var. Check your javascript console for errors. A little more context on what you tried would be helpful too. Commented Dec 13, 2013 at 19:03
  • Can you show the code you are using to obtain the JSON? Commented Dec 13, 2013 at 19:07
  • @JasonP Ops, I didn't name the variabile var, that was just to explain what I was doing. However, I just wanted to get that value with jQuery. @xaro Ok. Commented Dec 13, 2013 at 19:07
  • @Davide. Is there a particular reason you're doing a post? Check your error console, you're probably getting blocked by same origin restrictions. You'll probably need to use jsonp (if the service supports it) Commented Dec 13, 2013 at 19:14
  • @JasonP My error console says "[Error] TypeError: 'undefined' is not an object (evaluating 'data.track.listeners')" Commented Dec 13, 2013 at 19:16

2 Answers 2

1

If you save this JSON to a variable response, then using response.track.listeners you should have the value you want.

The JSON you posted is not an array. JSON arrays are delimited by [...], as can be seen in the array track.toptags.tag in your document.

Sign up to request clarification or add additional context in comments.

Comments

0
var my_json = {"track":{"id":"243317.....};

console.log(my_json.track.listeners);

...should be OK. But if you named your JSON object "var" it won't work (javascript keyword to declare a variable).

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.