google closure compiler and json

后端 未结 3 1325
礼貌的吻别
礼貌的吻别 2021-02-08 04:30

I have a json string that I parse and then access the properties of the object with the dot notation. However, in the google closure compiler, the dot notation (MyObject.P

3条回答
  •  执念已碎
    2021-02-08 04:39

    EDIT: the @expose directive has been deprecated


    Google Closure Compiler lets you specify directives on how compilation should be done through annotations.

    See: https://developers.google.com/closure/compiler/docs/js-for-compiler

    Properly using @expose and @type you can preserve the name of a property in your code.

    It is possible to safely decode a JSON string into an object and access that object using the dot notation. You'll be also able to stringify back the data.

    -

    Let's make an example:

    You want to parse an array of objects. Every object represents a "size", with the properties w for width and h for height.

    Declare a prototype for the size object and expose its properties w and h

    function size() {}
    
    /** @expose */
    size.prototype.w = 0;
    /** @expose */
    size.prototype.h = 0;
    

    Then you want to put the JSON parsed data into an array called data.

    Using @type you declare that data is going to hold an array of object of type size.

    function main()
    {
        /** @type {Array.} */
        var data;
    
        // string built up just for example purposes
        var response = '[{"w": 10, "h": 20}]';
    
        // parse the array
        var data = JSON.parse(response);
    
        // access data with dot notation!
        console.log(data[0].w+ "    "+ data[0].h);
    }
    
    main();
    

提交回复
热议问题