Created
March 23, 2016 12:15
-
-
Save HoffmannP/60f433ad2b8f9eadc014 to your computer and use it in GitHub Desktop.
See examples for GLib libsoup at http://bobthegnome.blogspot.de/2015/11/accessing-json-webservice-using-libsoup.html
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const Soup = imports.gi.Soup; | |
const Json = imports.gi.Json; | |
function assert(assertion) { | |
if (!assertion) { | |
throw "Error"; | |
} | |
} | |
/* Get the data using a HTTP GET */ | |
let session = Soup.Session.new(); | |
session.set_property(Soup.SESSION_USER_AGENT, "test-json"); | |
let message = Soup.Message.new('GET', "https://reviews.ubuntu.com/reviews/api/1.0/review-stats/any/any"); | |
assert(message != null) | |
let status_code = session.send_message(message); | |
assert(status_code == Soup.Status.OK) | |
/* Parse the data in JSON format */ | |
let parser = Json.Parser.new(); | |
let result = parser.load_from_data(message.response_body.data, -1); | |
assert(result); | |
/* The data should contain an array of JSON objects */ | |
let _root = parser.get_root(); | |
assert(_root.get_node_type() == Json.NodeType.ARRAY); | |
let array = _root.get_array(_root); | |
for (let i = 0; i < array.get_length(); i++) { | |
/* Get the nth object, skipping unexpected elements */ | |
let node = array.get_element(i); | |
if (node.get_node_type() != Json.NodeType.OBJECT) { | |
continue; | |
} | |
/* Get the package name and number of ratings from the object - skip if has no name */ | |
let object = node.get_object(); | |
let package_name = object.get_string_member("package_name"); | |
let ratings_total = object.get_int_member("ratings_total"); | |
if (package_name) { | |
print(package_name + ": " + ratings_total); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment