Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

How can I pull and use JSON data using javascript?

For example, the URL https://graph.facebook.com/btaylor has the following JSON:

{
   "id": "220439",
   "name": "Bret Taylor",
   "first_name": "Bret",
   "last_name": "Taylor",
   "link": "http://www.facebook.com/btaylor",
   "username": "btaylor",
   "gender": "male",
   "locale": "en_US"
}

How can I this data into javascript variables?

Not looking to use facebook API or anything dynamic right now, just getting JSON data from a static URL into javascript.

In PHP I could easily do this like:

$contents = file_get_contents($url);
$jsonObj = json_decode($contents);
echo "Name: ".$jsonObj->{'name'};
share|improve this question

2 Answers

up vote 2 down vote accepted

I recommend jQuery's $.getJson() method

http://api.jquery.com/jQuery.getJSON/

Live demo with your data here: http://jsfiddle.net/6ZeJ8/3/

Of course, you'll need jQuery to use this method, put this into the <head> of your HTML, should work just fine.

<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
share|improve this answer

You would need to use AJAX or a script loader to fetch your JSON string, then parse the JSON string.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.