JQ

JQ is a very cool tool for parsing the JSON from REST services

JQ gives you a quick way to parse & filter JSONs into arrays. For instance, a good use case is parsing the JSON response of a REST service into an array.

class.json
{
    'classes' : [
        {
            'class_name': '61a',
            'students': [
                {'name':'john', 'id':'1'},
                {'name':'kevin', 'id':'2'},
            ]
        },
        {
            'class_name': '61b',
            'students': [
                {'name':'alex', 'id':'3'},
                {'name':'bob', 'id':'4'},
            ]
        },
    ]
}

If we want an array of student-class memberships with all the meta-data down the tree captured, we can run a query like this.

jq [.classes[] | {class_name: .class_name, student: .students[] } | 
        {class_name: .class_name, name: .student.name, id: .student.id}]

This would produce an array of this kind:

[{class_name: 61a, student_name: john, id: 1}, ...]

I use this to wrap JQ for python:

jq('.classes[] | {class_name: .class_name, student: .students[] } | 
        {class_name: .class_name, name: .student.name, id: .student.id}').transform(class.json)

JQ Playground

Use a playground to make working with it much easier. Use this:

https://jqplay.org/

Last updated

Was this helpful?