blog.lexruee.ch
Yet another blog on the Web.

Some months ago I decided to learn more about the GNOME ecosystem. Overall, I'm amazed how accessible the GNOME Shell and the GNOME ecosystem is for web developers - at least in in theory.

GNOME users and enthusiasts may already know that lot of the gnome-shell is written in JavaScript. Moreover, the GNOME desktop provides JavaScript bindings, allowing GNOME developers to write their Gtk-based applications in JavaScript as well. In the GNOME ecosystem the component that runs JavaScript-based applications is called Gjs. By the way, a really nice Gjs/Gtk tutorial can be found here.

Anyways, I just came across the problem of reading and writing JSON files on a GNOME desktop. Fortunately, this task is pretty straightforward as the following listings demonstrate.

Reading JSON files:

#!/usr/bin/env gjs

// Import GLib to read and write files
const GLib = imports.gi.GLib;

// get the contents of the json file data.json
let [ok, contents] = GLib.file_get_contents('data.json');
if (ok) {
    let map = JSON.parse(contents);
    log(map);
}

Writing JSON files:

#!/usr/bin/env gjs

// Import GLib to read and write files
const GLib = imports.gi.GLib;

let map = {
    temperature: 20.1,
    humidity: 39.1
};

// create a json string and write the contents to the file data.json
let data = JSON.stringify(map, null, '\t');
GLib.file_set_contents('data.json', data);

Overall, it seems that we can just use Glib and the global JSON object to read and write JSON files:

  • GLib.file_get_contents - GLib function for reading file contents
  • GLib.file_set_contents - Glib function for writing file contents
  • JSON.parse - Global JavaScript function to parse json strings
  • JSON.stringify - Global JavaScript function to create a JSON string from a object
© Alexander Rüedlinger, 2017-2018
Proudly powered by Pelican, which takes great advantage of Python.