继续操作前请注册或者登录。

JSON


  • JSON is purely a string with a specified data format — it contains only properties, no methods.
  • JSON requires double quotes to be used around strings and property names. Single quotes are not valid other than surrounding the entire JSON string.
  • Even a single misplaced comma or colon can cause a JSON file to go wrong, and not work. You should be careful to validate any data you are attempting to use (although computer-generated JSON is less likely to include errors, as long as the generator program is working correctly). You can validate JSON using an application like JSONLint.
  • JSON can actually take the form of any data type that is valid for inclusion inside JSON, not just arrays or objects. So for example, a single string or number would be valid JSON.
  • Unlike in JavaScript code in which object properties may be unquoted, in JSON only quoted strings may be used as properties.



This  is a very useful JavaScript object that allows us to make network requests to retrieve resources from a server via JavaScript (e.g. images, text, JSON, even HTML snippets), meaning that we can update small sections of content without having to reload the entire page。


let requestURL = 'https://mdn.github.io/learning-area/javascript/oojs/json/superheroes.json';
let request = new XMLHttpRequest();
request.open('GET', requestURL)
request.responseType = 'json';  
// XHR knows that the server will be returning JSON,
// and that this should be converted behind the scenes into a JavaScript object.
// Then we send the request with the send() method
request.send();

The XMLHttpRequest method send() sends the request to the server.


This takes at least two parameters — there are other optional parameters available. We only need the two mandatory ones for this simple example:

  • The HTTP method to use when making the network request. In this case GET is fine, as we are just retrieving some simple data.
  • The URL to make the request to — this is the URL of the JSON file that we stored earlier.

The last bit of this section involves waiting for the response to return from the server, then dealing with it. Add the following code below your previous code:

request.onload = function() {
  const superHeroes = request.response;
  populateHeader(superHeroes);
  showHeroes(superHeroes);
}

上面的设置好了后,最后send(),发送请求, send the request.
request.send();

we set the XHR request to convert the JSON response directly into a JavaScript object using:

request.responseType = 'json';

sometimes we receive a raw JSON string


  • parse(): Accepts a JSON string as a parameter, and returns the corresponding JavaScript object.
  • stringify(): Accepts an object as a parameter, and returns the equivalent JSON string.


-ify  动词后缀,使string化

let myObj = { name: "Chris", age: 38 };
myObj
let myString = JSON.stringify(myObj);
myString
阅读量: 617
发布于:
修改于: