Skip to content

Fields

You can filter JSON fields easily using a GraphQL-like syntax regardless if it is deeply nested or if it is inside an array.

Simple filtering

Given this input JSON:

input.json
{
"id": 1,
"customer": {
"firstName": "Jhon",
"lastName": "Doe"
}
}

Say that we only want to retain the firstName field of the customer object. We can achieve it by using the query:

query.gq
{
customer {
firstName
}
}
output.json
{
"customer": {
"firstName": "Jhon"
}
}

Dot operator

Additionaly, you can access nested fields using the dot operator.

input.json
{
"title": "Countries",
"release": {
"year": 2021,
"month": "September"
},
"countries": [
{
"name": "United States",
"capital": "Washington, D.C."
},
{
"name": "Canada",
"capital": "Ottawa"
},
{
"name": "Australia",
"capital": "Canberra"
}
]
}

Say that we only want to get the release year but this time, we only want the raw number. We can obtain it with the following query:

query.gq
release.year
output.json
2021

Furthermore, the dot operator can also be applied to array fields in order to perform effectively a mapping into all the elements:

query.gq
countries.name
output.json
["United States", "Canada", "Australia"]

Naturally, you can also mix both the dot operator and the simple filtering:

query.gq
{
release
countries.capital
}
output.json
{
"release": {
"year": 2021,
"month": "September"
},
"capital": [
"Washington, D.C.",
"Ottawa",
"Canberra"
]
}

Special key names

If you have a JSON with non-standard key names, you can double-quote them to match them. This includes keys with spaces, special UTF-8 characters or custom language reserved words. Let’s take a look at an example:

input.json
{
"证明": "Test",
"Key with spaces": {
"one": 1,
"two": 2
}
}

In this case, we want to get the 年份 field. We can achieve it by using the following query:

query.gq
"证明"
output.json
"Test"

Or if you have a key with spaces:

query.gq
"Key with spaces".one
output.json
1

Order preservation

GQ preserves the same order of the fields specified in the query when generating the output JSON. This means that GQ can even be used to rearrange your JSONs.

For example, if you have the following JSON containing objects with unordered keys:

input.json
[
{
"name": "Chris",
"age": 23,
"lastName": "Stuart"
},
{
"age": 10,
"lastName": "Sanchez",
"name": "Ana"
}
]

You can order them by simply using the following query:

query.gq
{
name
lastName
age
}
output.json
[
{
"name": "Chris",
"lastName": "Stuart",
"age": 23
},
{
"name": "Ana",
"lastName": "Sanchez",
"age": 10
}
]