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:
{ "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:
{ customer { firstName }}{ "customer": { "firstName": "Jhon" }}Dot operator
Additionaly, you can access nested fields using the dot operator.
{ "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:
release.year2021Furthermore, the dot operator can also be applied to array fields in order to perform effectively a mapping into all the elements:
countries.name["United States", "Canada", "Australia"]Naturally, you can also mix both the dot operator and the simple filtering:
{ release countries.capital}{ "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:
{ "证明": "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:
"证明""Test"Or if you have a key with spaces:
"Key with spaces".one1Order 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:
[ { "name": "Chris", "age": 23, "lastName": "Stuart" }, { "age": 10, "lastName": "Sanchez", "name": "Ana" }]You can order them by simply using the following query:
{ name lastName age}[ { "name": "Chris", "lastName": "Stuart", "age": 23 }, { "name": "Ana", "lastName": "Sanchez", "age": 10 }]