json_dumps

The `json_dumps` directive outputs a JSON representation of a specified JSON variable into a string variable.

Syntaxjson_dumps $string $json [name ...];
Defaultnone
Contexthttp, server, location
Arguments2+

Description

The json_dumps directive is designed to convert a JSON variable (which is stored in a specific format in NGINX) back into a string representation. This is especially useful when you need to serialize JSON data for logging, displaying in responses, or further processing within your NGINX configuration. This directive allows you to specify the target variable where the JSON data will be dumped, along with optional keys or indices if you are dealing with JSON objects or arrays.

When you specify the json_dumps directive in your NGINX configuration, it expects at least two parameters: the destination string variable and the JSON variable to be dumped. If the JSON data is an object or an array, you can specify which element to extract using additional keys or indices. The function handles different scenarios, ensuring proper logging for debugging if extraction or conversion fails. Additionally, various flags during the dumps (like JSON_PRESERVE_ORDER, JSON_ENCODE_ANY, and JSON_COMPACT) are used to configure the output format depending on the needs of your application.

This directive can be utilized within contexts such as http, server, and location, providing significant flexibility in how you handle JSON data across different parts of your application. It integrates seamlessly with existing NGINX variable management systems, leveraging NGINX’s performance and efficiency in processing requests.

Config Example

location /example {
    json_load $request_body json_data;
    json_dumps $output_var json_data;
}

Ensure the JSON variable is properly loaded using the json_load directive before using json_dumps.

Be cautious of the types of the keys used for JSON objects or indices for arrays; provide valid ones to avoid errors.

The length of the JSON variable must be verified; unexpected lengths can lead to crashes or invalid output.

← Back to all directives