{
and a }
.
These properties and their values are often referred to as "key-value pairs".
However, JSON transmitted by APIs are sent as bytes
, and your application receives it as a string
. These can be converted into JavaScript objects, but they are not JavaScript objects by default. The JSON.parse
method parses the string and constructs the JavaScript object described by it.
You can request the JSON from freeCodeCamp's Cat Photo API. Here's the code you can put in your click event to do this:
req=new XMLHttpRequest();Here's a review of what each piece is doing. The JavaScript
req.open("GET",'/json/cats.json',true);
req.send();
req.onload=function(){
json=JSON.parse(req.responseText);
document.getElementsByClassName('message')[0].innerHTML=JSON.stringify(json);
};
XMLHttpRequest
object has a number of properties and methods that are used to transfer data. First, an instance of the XMLHttpRequest
object is created and saved in the req
variable.
Next, the open
method initializes a request - this example is requesting data from an API, therefore is a "GET" request. The second argument for open
is the URL of the API you are requesting data from. The third argument is a Boolean value where true
makes it an asynchronous request.
The send
method sends the request. Finally, the onload
event handler parses the returned data and applies the JSON.stringify
method to convert the JavaScript object into a string. This string is then inserted as the message text.
XMLHttpRequest
.
testString: 'assert(code.match(/new\s+?XMLHttpRequest\(\s*?\)/g), "Your code should create a new XMLHttpRequest
.");'
- text: Your code should use the open
method to initialize a "GET" request to the freeCodeCamp Cat Photo API.
testString: 'assert(code.match(/\.open\(\s*?("|")GET\1\s*?,\s*?("|")\/json\/cats\.json\2\s*?,\s*?true\s*?\)/g), "Your code should use the open
method to initialize a "GET" request to the freeCodeCamp Cat Photo API.");'
- text: Your code should use the send
method to send the request.
testString: 'assert(code.match(/\.send\(\s*\)/g), "Your code should use the send
method to send the request.");'
- text: Your code should have an onload
event handler set to a function.
testString: 'assert(code.match(/\.onload\s*=\s*function\(\s*?\)\s*?{/g), "Your code should have an onload
event handler set to a function.");'
- text: Your code should use the JSON.parse
method to parse the responseText
.
testString: 'assert(code.match(/JSON\.parse\(.*\.responseText\)/g), "Your code should use the JSON.parse
method to parse the responseText
.");'
- text: Your code should get the element with class message
and change its inner HTML to the string of JSON data.
testString: 'assert(code.match(/document\.getElementsByClassName\(\s*?("|")message\1\s*?\)\[0\]\.innerHTML\s*?=\s*?JSON\.stringify\(.+?\)/g), "Your code should get the element with class message
and change its inner HTML to the string of JSON data.");'
```
```