Photo by Drew Beamer on Unsplash

Automate the Boring Stuff – Transform a QGIS Style XML to Mapbox JSON

  • Javascript
  • Programming
  • Software Development
  • Technology
  • Web development
  • Par Tarek Baaga, le 22 juin 2021

    In this article, we will use Node.js to automate the generation of a JSON style file from a QGIS XML style file. The style generation script is key for any team working in an iterative design process with multiple parties.

    A little context

    As we are using Mapbox GL JS we need the style to be in a JSON form. Our data scientists are the classification experts. After finding the right classification for a layer in QGIS, the style layer is forwarded to our front-end development team. We ended up spending a significant amount of time copying hex color codes between the style layer and our Mapbox style definitions. The Mapbox style is used for the cartographic legend and the layer style.

    We came to the conclusion that the ROI of an internal tool for converting QGIS style layers to an interpretable JSON by Mapbox was well worth the investment.

    How it works?

    Being frontend developers, we have a preference for JavaScript. By using Node.js, we had access to a ton of cool packages from npm:

    To be able to use it in every situation (or at least the situation that we know 😀) we created 2 scripts. The first one is named onecategory.js work when one value is associated with one color like in this image:

    Legend representing a property with one value and one color.

    All you have to do is run the script from the command line of the root of the project like this:

    node onecategory.js ‘onecolorlive.xml’ ‘onevalueonecolor.json’

    After this command is run, a JSON is generated like this:


    For the second script, If you have a range of values associated with one color that looks like this: 

    Legend representing a property with range of values and one color.

    Then it would be the same process but this time you have to use the other script file named rangevalue.js:

    node rangevalue.js ‘colorslive.xml’ ‘rangecolorvalues.json’

    Final thoughts

    When you don’t have a lot of data, it’s not too time-consuming to manually transfer a style. You can and copy the hex color codes one by one, but there is eventually a limit to the manual process. If you have a layer that has multiple ranges of values associated with different colors, doing this process manually can be very long and frustrating. Especially, when you have product managers or data scientists consistently requesting style changes. By using this script, you keep focused on what’s important and you don’t fall into the process of repeating something multiple times in a day. Hopefully, this tool will help you iteratively test out new styles and build products customers love.

    This is the repository of the project, so you can clone it use it for yourself, and save precious time!!