Mapping Arrays
Transform JSON arrays and objects into GraphQL lists
In Apollo Connectors selection mapping, array handling happens automatically, so you must ensure that your schema uses list types appropriately.
Example array handling
For example, given the following JSON response:
{
"results": [
{
"id": "1",
"variants": [
{ "id": "1", "color": "Silver" },
{ "id": "2", "color": "Platinum" }
],
"reviews": ["Best purchase ever!", "Good value"]
}
]
}
You can use the following selection mapping:
1type Query {
2 products: [Product] # List 1
3 @connect(
4 http: { GET: "https://ecommerce.demo-api.apollo.dev/products" }
5 selection: """
6 $.results { # Populates list 1
7 id
8 variants { # Populates list 2
9 id
10 type: color
11 }
12 reviews # Populates list 3
13 }
14 """
15 )
16}
17
18type User {
19 id: ID!
20 variants: [Variant] # List 2
21 reviews: [String] # List 3
22}
23
24type Variant {
25 id: ID!
26 color: String
27}
List management
Various methods, including ->first
, ->last
, ->slice
, and ->size
, let you transform lists.
For example, to transform a list into its first value, use ->first
like so:
color->first
{
"color": ["red", "green", "blue"]
}
{
"color": "red"
}
To wrap a single item in a list, you can use a literal list and select the property:
$([$.color])
{
"color": "red"
}
{
"color": ["red"]
}
Convert a map into a list of key-value pairs
Converting a map into a list of key-value pairs is particularly useful when you need to work with data in a more structured or iterable format. For example, in a frontend application, you might want to render a list of items, such as color names and their corresponding hex codes.
The example below uses the ->entries
method to convert a map of color names and hex codes into a list of objects. You can use the following selection mapping snippet:
colors: colors->entries
To transform response data like this:
{
"colors": {
"red": "#ff0000",
"green": "#00ff00",
"blue": "#0000ff"
}
}
{
"colors": [
{ "key": "red", "value": "#ff0000" },
{ "key": "green", "value": "#00ff00" },
{ "key": "blue", "value": "#0000ff" }
]
}
To use different names for keys and values, select the fields with aliases:
colors: colors->entries {
name: key
hex: value
}
{
"colors": {
"red": "#ff0000",
"green": "#00ff00",
"blue": "#0000ff"
}
}
{
"colors": [
{ "name": "red", "hex": "#ff0000" },
{ "name": "green", "hex": "#00ff00" },
{ "name": "blue", "hex": "#0000ff" }
]
}
Additional resources
Refer to the mapping language reference for a complete overview of mapping syntax and usage.
The methods reference lists all available object and array methods.