What is JSON? Data format prepared for JavaScript

Source: Internet
Author: User
Tags control characters tojson

What is JSON? Data format prepared for JavaScript

Not yet understand what JSON is? After reading this article, you should be able to have a clearer idea of what JSON is.

JSON is JavaScript. Object Natation, which is a lightweight data interchange format, is well suited for server and JavaScript. The interaction. This article will quickly explain the JSON format and demonstrate how to handle JSON-formatted data on both the client and server side, using code examples.

While there is a lot of hype about how XML has cross-platform, cross-language benefits, unless applied to web Services, developers often have a headache with parsing XML, whether it's server-side generation or processing of XML, or client Javascript. Parsing XML often leads to complex code and very low development efficiency. In fact, for most Web applications, they don't need complex XML to transmit data at all, and XML extensibility is rarely an advantage, and many AJAX applications even return HTML fragments directly to build dynamic Web pages. Returning HTML fragments greatly reduces the complexity of the system compared to returning XML and parsing it, but at the same time lacks some flexibility.

Now, JSON provides another form of data interchange for WEB app developers. Let's take a look at what JSON is, and JSON provides better simplicity and flexibility than XML or HTML fragments.

JSON Data Format parsing

As with XML, JSON is also a data format based on plain text. Because JSON is inherently JavaScript-only. Prepared, therefore, the JSON data format is very simple, you can transfer a simple string,number,boolean with JSON, you can also transfer an array, or a complex object.

String,number and Boolean representations of JSON are very simple. For example, use JSON to represent a simple String "ABC" in the form of:

"ABC"

In addition to the characters ", \,/and some control characters (\b,\f,\n,\r,\t) need to be encoded, other Unicode characters can be output directly.

This is consistent with the representation of most programming languages, such as:

    1. 12345 (integer)
    2. -3.9e10 (floating point)

The Boolean type is expressed as true or false. In addition, JavaScript. The null in is represented as NULL, and note that true, FALSE, and null do not have double quotes, otherwise they will be treated as a String.

JSON can also represent an array object, using [] contains all elements, each element is separated by commas, and the element can be any Value, for example, the following array contains a string,number,boolean and a null:

["ABC", 12345,false,null]

Object objects are represented in JSON with a series of unordered Key-value key-value pairs, in fact the object here is equivalent to map<string in Java, Object>, rather than Java Class. Note that Key can only be represented by String.

For example, an Address object contains the following key-value:

    1. City:beijing
    2. Street:chaoyang Road
    3. postcode:100025 (integer)

This is represented by JSON:

    1. {"City": "Beijing", "Street": "Chaoyang Road", "Postcode": 100025}

Where Value can also be another object or an array, complex objects can be nested representations, for example, a person object that contains a name and address object, which can be represented as follows:

    1. {"Name": "Michael", "Address":
    2. {"City": "Beijing", "Street": "Chaoyang Road", "Postcode": 100025}
    3. }

Javascript. Working with JSON data

The above describes how to represent data in JSON, and then we will also work out how to generate JSON-formatted data on the server side to send to the client and how the client uses JavaScript. Processes data in JSON format.

Let's discuss how to work with JavaScript in Web pages. Process JSON data. We pass a simple JavaScript. method to see how the client can represent the JSON data to the user:

    1. function Handlejson () {
    2. var j={"name":"Michael","address":
    3. {"city":"Beijing","street":"Chaoyang Road","postcode": 100025}
    4. };
    5. document.write (J.name);
    6. document.write (j.address.city);
    7. }

Assume that the JSON data returned by the server is the above:

    1. {"Name": "Michael", "Address":
    2. {"City": "Beijing", "Street": "Chaoyang Road", "Postcode": 100025}
    3. }

Just assign it to a JavaScript. Variable, you can immediately use the variable and update the information in the page, which is very easy to use when the XML needs to read the various nodes from the DOM. All we need to do is send an AJAX request and assign the JSON data returned by the server to a variable. There are many Ajax frameworks that already contain the ability to process JSON data, such as Prototype, a popular JavaScript. Library: http://prototypejs.org) provides the Evaljson () method to directly convert the JSON text returned by the server into a JavaScript. Variable:

    1. New Ajax.request ("Http://url", {
    2. Method: "Get",
    3. Onsuccess:function (transport) {
    4. var json = Transport.responseText.evalJSON ();
    5. //TODO:document.write (JSON.XXX);
    6. }
    7. });

Server-side output JSON format data

Here we discuss how to output JSON-formatted data on the server side. In Java, for example, we will demonstrate the encoding of a Java object into JSON-formatted text.

When you encode a String object in JSON format, you only need to handle the special characters. In addition, the string must be represented by (") rather than ('):

  1. Static String String2json (string s) {
  2. StringBuilder sb = new StringBuilder (S.length () +20);
  3. Sb.append (' \ ');
  4. For (int i=0; i<s.length (); i++) {
  5. char c = s.charat (i);
  6. switch (c) {
  7. case ' \ ':
  8. Sb.append ("\\\");
  9. Break ;
  10. case ' \ \ ':
  11. Sb.append ("\\\\");
  12. Break ;
  13. case '/':
  14. Sb.append ("\\/");
  15. Break ;
  16. case ' \b ':
  17. Sb.append ("\\b");
  18. Break ;
  19. case ' \f ':
  20. Sb.append ("\\f");
  21. Break ;
  22. case ' \ n ':
  23. Sb.append ("\\n");
  24. Break ;
  25. case ' \ R ':
  26. Sb.append ("\\r");
  27. Break ;
  28. case ' \ t ':
  29. Sb.append ("\\t");
  30. Break ;
  31. Default:
  32. Sb.append (c);
  33. }
  34. }
  35. Sb.append (' \ ');
  36. return sb.tostring ();
  37. }

It is much easier to represent number as JSON, and with Java polymorphism, we can deal with integer,long,float, and so on.

    1. Static String Number2json (number number) {
    2. return number.tostring ();
    3. }

The Boolean type can also get the JSON representation directly through the ToString () method:

    1. Static String Boolean2json (Boolean bool) {
    2. return bool.tostring ();
    3. }

To encode an array into JSON format, you can encode each element through a loop:

  1. Static String Array2json (object[] array) {
  2. if (array.length==0)
  3. return "[]";
  4. StringBuilder sb = new StringBuilder (Array.Length << 4);
  5. Sb.append (' [');
  6. For (Object o:array) {
  7. Sb.append (ToJson (o));
  8. Sb.append (', ');
  9. }
  10. //The last added ', ' becomes '] ':
  11. Sb.setcharat (Sb.length ()-1, '] ');
  12. return sb.tostring ();
  13. }

Finally, we need to encode map<string, object> into JSON format because of JavaScript. The Object actually corresponds to the Java map<string, object>. The method is as follows:

  1. Static String Map2json (map<string, object> Map) {
  2. if (Map.isempty ())
  3. return "{}";
  4. StringBuilder sb = new StringBuilder (Map.size () << 4);
  5. Sb.append (' {');
  6. set<string> keys = Map.keyset ();
  7. For (String key:keys) {
  8. Object value = Map.get (key);
  9. Sb.append (' \ ');
  10. Sb.append (key);
  11. Sb.append (' \ ');
  12. Sb.append (': ');
  13. Sb.append (ToJson (value));
  14. Sb.append (', ');
  15. }
  16. //Change the last ', ' to '} ':
  17. Sb.setcharat (Sb.length ()-1, '} ');
  18. return sb.tostring ();
  19. }

To unify the processing of arbitrary Java objects, we write an ingress method, ToJson (object), that encodes any Java object into JSON format:

  1. Public static String ToJson (Object o) {
  2. if (o==null)
  3. return "null";
  4. if (o instanceof String)
  5. return String2json (String) o;
  6. if (o instanceof Boolean)
  7. return Boolean2json ((Boolean) o);
  8. if (o instanceof number)
  9. return Number2json ((number) O);
  10. if (o instanceof Map)
  11. return Map2json ((map<string, object>) o);
  12. if (o instanceof object[])
  13. return Array2json ((object[]) o);
  14. throw New RuntimeException ("Unsupported type:" + O.getclass (). GetName ());
  15. }

We do not have strict checks on Java objects. Objects that are not supported (such as List) will throw runtimeexception directly. In addition, to ensure that the output JSON is valid, map<string, the Object> object's Key cannot contain special characters. The attentive reader may also find that the loop-referenced object throws infinite recursion, for example, by carefully constructing a circular-referenced Map, the StackOverflowException can be detected:

    1. @Test (expected=stackoverflowerror. class)
    2. Public void Testrecurrsivemap2json () {
    3. map<string, object> map = new hashmap<string, object> ();
    4. Map.put ("key", map);
    5. Jsonutil.map2json (map);
    6. }

Fortunately, the JSON data processed by the server should eventually be translated into simple JavaScript. object, so the likelihood of a recursive reference is small.

Finally, when you output JSON through a Servlet or MVC framework, you need to set the correct MIME type (Application/json) and character encoding. Assuming that the server uses UTF-8 encoding, you can output the encoded JSON text using the following code:

    1. Response.setcontenttype ("Application/json;charset=utf-8");
    2. Response.setcharacterencoding ("UTF-8");
    3. PrintWriter pw = Response.getwriter ();
    4. Pw.write (Jsonutil.tojson (obj));
    5. Pw.flush ();

Summary

JSON is already JavaScript. Part of the standard. Currently, the mainstream browser is perfect for JSON support. Using JSON, we can get rid of the parsing of XML, and for those Web 2.0 Web sites that apply Ajax, JSON is really the most flexible lightweight solution available today.

What is JSON, now you should know it.

What is JSON? Data format prepared for JavaScript

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.