Using Google's Closure Compiler to Optimize JSON Files

When dealing with a json string that is parsed and properties of the object are accessed using dot notation, a warning may be triggered by the google closure compiler stating that the property is not defined.

To overcome this issue, one workaround is to convert the code into bracket notation (MyObject['PropertyName']) which removes the warning but hinders the compiler's optimizations. However, when using JSON.stringify(MyObject), the server can receive a string with understandable property names.

Therefore, the question arises: How can we effectively utilize the google compiler in advanced mode when working with json objects that undergo deserialization and serialization at runtime?

Answer №1

When dealing with JSON objects, you have a couple of options:

  1. Access object properties using the string literal (e.g., MyJsonObject['PropertyName']) for a straightforward approach.
  2. Create an external file that outlines the properties in your JSON object and then utilize dot notation (e.g., MyJsonObject.PropertyName). While this method requires more upkeep, it allows for type checking by the compiler if type annotations are provided in the external description.

Answer №2

If you are solely using JavaScript to access external json data, it may negate the purpose of utilizing a compiler. However, if your JavaScript involves more tasks beyond just parsing json into domain models, then the compiler can prove to be beneficial.

In our parsing process, we retrieve data using bracket notation and then organize it into our own models, which provide us with type checking and other advantages.

When it comes to handling data, I make use of the XHRManager class, which has been incredibly useful for managing data events efficiently.

/**
 * @private
 * @param {goog.events.Event} evt Event received from XhrIo.
 */
mypath.MyClass.prototype.onDataRecieved_ = function(evt) {
  if (evt.type != 'complete') return;
  var xhrIo = evt.target;
  var data = xhrIo.getResponseJson();
  //do something!
};

I must admit that my handling of XHRManager is still a work in progress, as I only recently started implementing it in my codebase.

For parsing tasks, I follow this approach: (Please excuse any rough portions from my code snippet.)

our.class.path.ContestJsonParser.prototype.setContestProperties =
    function(contest, element) {
  contest.setName(element['description']);
  /**
     * @type {!number}
     */
  var timeAsInt = element['startTime'];
  contest.setScheduledStartTime(timeAsInt);
  var clockModel = contest.getClockModel();
  if (goog.isDefAndNotNull(element['period'])) {
    clockModel.setMatchState(element['period']['periodName']);
    clockModel.setStateStartTime(element['period']['periodStartTime']);
  }
  //TODO (Johan) this needs to change today to consider the rest of the stats
  //information
  var stats = element['statistics'];
  if (goog.isObject(stats) && goog.isDefAndNotNull(stats['score'])) {
    var score = stats['score'];
    contest.setMatchScore(score['home'], score['away']);
  } else {
    contest.setMatchScore(undefined, undefined); // clears score.
  }
};

Answer №3

NOTE: The use of the @expose directive has been deprecated


Google Closure Compiler allows for specifying directives on how compilation should be handled using annotations.

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

By correctly utilizing @expose and @type, you can maintain the name of a property in your code.

You can safely decode a JSON string into an object and access that object using dot notation. Additionally, you'll be able to stringify the data back.

-

Let's illustrate with an example:

Say you want to interpret an array of objects. Each object represents a "size", with the properties w for width and h for height.

Create 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;

Next, you aim to insert the JSON parsed data into an array named data.

Using @type, specify that data will contain an array of objects of type size.

function main()
{
    /** @type {Array.<size>} */
    var data;

    // creating a sample response string
    var response = '[{"w": 10, "h": 20}]';

    // parsing the array
    var data = JSON.parse(response);

    // accessing data using dot notation!
    console.log(data[0].w+ "    "+ data[0].h);
}

main();

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Guide on importing table information into an array using jQuery

I am facing an issue where I want to extract values from a dynamically generated table and then send those values in an AJAX call. The problem is that even though I am able to increase the number of rows in the table dynamically, when I try to capture the ...

Is there a way for me to verify if I have already made an AJAX data request

I have an image gallery with thumbnails. When a user clicks on a thumbnail, an ajax request is fired. I want to prevent the ajax request from firing again if the user clicks on the same thumbnail and instead use the existing data. $.getJSON(url, function( ...

Node.js can be used to easily set the values of HTML elements

After successfully setting up a node.js connection to my mysql database and being able to retrieve and input data using connection.query(), I now want to display the database information on my HTML elements. Is there an equivalent of getElementById for t ...

Issues with sending empty strings to an API in Vue Js

My code below is designed to update data using a Node Js REST API. The remaining field contains an equation using v-model=remaininginst to calculate and store the result in remaininginst. However, when I check the console.log, I am getting NaN empty data s ...

Attempting to retrieve information from PHP using JSON for communication with Android

Struggling to fetch information from PHP using JSON in an Android app. Here is the PHP script I am using: <?php # print(json_encode("[name=john]")); # ?> However, when trying to receive this data in Java, I encounter the following error: ERROR/log ...

My date function in Node JS is throwing an error, can someone please help me troubleshoot?

I encountered an error with new date(); while working with node js and express npm plugin. I built a variable date but faced some compilation errors. This is my code .js var update_time = new Date(); update_time.formatDate("y/m/d"); When I run ...

Effects of jQuery Show / Hide on adjacent select box operations

I created a pair of select boxes where the visibility of one is controlled by the other. Initially, the controlled select box (#select02) works perfectly on page load as long as I don't show/hide it by selecting options in the controlling select box ( ...

I need to mass upload a collection of resumes stored in a zip file, then extract and display the content of each resume using a combination of HTML

I recently used a service to extract and retrieve the contents of a zip file. I am trying to read the content of the files and integrate them into the scope of my Angular project. Any suggestions would be greatly appreciated. Below is an outline of my func ...

I'm having trouble figuring out why my Vue method isn't successfully deleting a Firebase object. Can anyone offer some guidance

What I am trying to achieve: I have been struggling to use the remove method from Firebase. I have read the documentation, but for some reason, it is not working as expected. Retrieving data using snapshot works fine, but when I try to delete using the re ...

What is the best way to implement an 'onKeyPress' event listener for a <canvas> element in a React application?

I've been working with React for a while now and I understand how its event system functions. However, I've run into an issue where the onKeyPress event doesn't seem to be triggering on a <canvas> element. Surprisingly, it's not w ...

Converting a file from a URL to a blob in PHP for use in JavaScript

Attempting to convert an image from a URL to a blob file that can be utilized in JavaScript, but encountering challenges. Is this achievable and if so, how? Current attempts include: // $request->location is the url to the file in this case an ima ...

Javascript encountered an error upon attempting to return from the main function

I have a function that calls the database to perform an action: function callQuery(query) { db.query(query, (err, res) => { if (err) { // Error connecting to DB console.log(err.stack) } else { // Return the results ret ...

``The presence of symlink leading to the existence of two different versions of React

Currently, I am working on a project that involves various sub custom npm modules loaded in. We usually work within these submodules, then publish them to a private npm repository and finally pull them into the main platform of the project for use. In orde ...

Testing abstract class methods in Jest can ensure full coverage

In my project, I have an abstract generic service class. export default abstract class GenericService<Type> implements CrudService<Type> { private readonly modifiedUrl: URL; public constructor(url: string) { this.modifiedUrl = ...

Enhancing Request JSON Body Validation in Next.js 14 API Handler

I'm currently in the process of developing an API for my iOS application using Next.js 14. I have managed to get it up and running successfully, however, I am facing some challenges when it comes to properly validating the body of a request. ESLint is ...

Utilizing jQuery to update dropdown selection based on JSON object values

In my JSON value, I have the following roles: var roles = { "roles":[ {"role_id":2,"role_name":"admin"}, {"role_id":4,"role_name":"QA"}, {"role_id":3,"role_name":"TL"}, {"role_id":5,"role_name":"user"}, {"role_id":1,"role_name":"r ...

Creating dictionary data in JSON format using Python is a simple process

As a newcomer to Python, I am currently grappling with understanding how to work with dictionaries operations. Here is the data that I have: [{'mesure':'10', 'name': 'mumbai', 'age': '15', &apos ...

Traversing a two-dimensional array backwards in JavaScript

I am working with an array that contains different teams: The structure looks like this: leagues = new Array( Array('Juventus'), Array('Milan'), Array('Inter')); My goal is to iterate through the array and generat ...

Activate a button by simulating a click event through a shortcut key with the help of a

I have incorporated the hotkeys plugin to enable shortcut functionality on my website. Currently, I am looking for a way to automatically trigger a button click when any shortcuts are pressed. hotkeys.add({ combo: 'alt+1', callback: function (da ...