json_var

The `json_var` directive creates a new variable in NGINX that aggregates multiple values into a JSON object.

Syntaxjson_var $variable { ... }
Defaultnone
Contexthttp
Argumentsblock (1)

Description

The json_var directive allows administrators to define a block of key-value pairs that are transformed into a JSON format. Each key-value pair is defined within the json_var block, where the key is a string identifier and the value can be any valid NGINX variable. This is particularly useful for returning structured data to clients in a consistent format, such as API responses. The directive's context is limited to the http block, making it applicable for server-wide settings but not within individual server or location blocks.

When the json_var directive is declared, it initializes an internal structure to hold fields specified within its block. For each specified field, NGINX compiles it into a complex value, allowing for dynamic calculation of values (e.g., based on request variables). Once configured, the resulting variable can be used directly in NGINX responses, typically within the return directive or similar context to output the JSON-formatted string to the client. The directive handles variable escaping as needed, ensuring that the produced JSON is valid.

Config Example

http {
    json_var $output {
        timestamp $time_local;
        remoteAddr $remote_addr;
        xForwardedFor $http_x_forwarded_for;
        userAgent $http_user_agent;
        params $args;
    }
    
    server {
        location /get_json/ {
            return 200 $output;
        }
    }
}

Ensure that the json_var block contains the correct number of arguments for each key-value pair, as improper configuration can lead to initialization errors.

Be cautious with NGINX variable names; ensure they are correctly defined and valid within the scope of the NGINX configuration.

Remember to escape JSON values where necessary to maintain proper formatting.

← Back to all directives