What is JSON and why would I use it?

前端 未结 17 1854
说谎
说谎 2020-11-21 15:54

I\'ve looked on wikipedia and Googled it and read the official documentation, but I still haven\'t got to the point where I really understand what JSON is, and why I\'d use

17条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-21 16:24

    In short - JSON is a way of serializing in such a way, that it becomes JavaScript code. When executed (with eval or otherwise), this code creates and returns a JavaScript object which contains the data you serialized. This is available because JavaScript allows the following syntax:

    var MyArray = [ 1, 2, 3, 4]; // MyArray is now an array with 4 elements
    var MyObject = {
        'StringProperty' : 'Value',
        'IntProperty' : 12,
        'ArrayProperty' : [ 1, 2, 3],
        'ObjectProperty' : { 'SubObjectProperty': 'SomeValue' }
    }; // MyObject is now an object with property values set.
    

    You can use this for several purposes. For one, it's a comfortable way to pass data from your server backend to your JavaScript code. Thus, this is often used in AJAX.

    You can also use it as a standalone serialization mechanism, which is simpler and takes up less space than XML. Many libraries exists that allow you to serialize and deserialize objects in JSON for various programming languages.

提交回复
热议问题