Skip to content

Instantly share code, notes, and snippets.

@HoffmannP
Created March 23, 2016 12:15
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save HoffmannP/60f433ad2b8f9eadc014 to your computer and use it in GitHub Desktop.
Save HoffmannP/60f433ad2b8f9eadc014 to your computer and use it in GitHub Desktop.
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