Converting JSON to JS

A short entry to the json-to-js utility

Imagem de capa

Every now and again you find yourself doing the same repetitive task over and over again. I just happened to face such a task, as I was refactoring code that loaded JSON into a Jassmine test.

So, what’s wrong with that?

…You might ask!

Well, separating test data from a unit test is bad practice, even though it may increase re-usability. This is due to the fact that test data is imperative to the tests being written.

So, to take this full circle, I was finding myself taking json syntax, as:

{
  "test": "data",
  "numeric": 42,
  "complex": {
    "name": "John Doe",
    "occupation": "Assassin"
  }
}

into javascript object notation, as:

const data = {
  test: 'data',
  numeric: 42,
  complex: {
    name: 'John Doe',
    occupation: 'Assassin'
  }
}

Solutions

So, as any developer I first took “the manual, believed to be easy - however proving to be slow approach”.

The manual approach

Converting a file by copying the JSON structure into the JS file was the first approach I chose. Initially I didn’t see a problem with this solution.

It was a task of:

  1. Copy the JSON structure to a JS file.
  2. Remove quotation marks from property names.
  3. Replace quotation marks from string values, with apostrophes

Did it take long for a single file… well, no? Did I have more than a single file… yes, so I got bored fairly quickly doing so!

Using my IDE

My next idea was to use my IDE to solve the problem - I am using Webstorm, btw. But unfortunately I didn’t find any build-in functionality nor a plugin to resolve the problem at hand.

If I had been using Visual Studio Code, then I would have been more at luck. I managed to find the JSON to JS Object plugin - but as already mentioned, it’s not my first choice of IDE.

Using a CLI

My final way out, would be to use a CLI tool. Granted, it wouldn’t be a solution integrated into my IDE - however that’s not too big of a deal, since I already seem to spend a great deal of my development time in the terminal.

I happened to go with the tool json-to-js (you can find instructions on how-to install the tool on their website).

I simply added an alias to my shell-interpreter, eg.:

alias j2j="pbpaste | json-to-js | pbcopy"

Doing so I was able to:

  1. Copy the JSON structure (to clipboard)
  2. Execute j2j in my terminal
  3. Paste the JS code from my clipboard to my IDE

Conclusion

I managed to reduce the time spend doing the task - but I can see myself improving the solution even further. I should be able to either bind a keyboard shortcut (either in my IDE, or in MacOS) to run the terminal alias I had created.

I havn’t gotten that far, though… I’ll update this post if I ever get around to it!