Smart Systems for Home

Plain how-to guides for smart home, security and home Wi-Fi

PostgreSQL json_extract_path_text: Usage and Examples

· 4 min read · Home Tech

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

The json_extract_path_text function in PostgreSQL is used to retrieve a specific value from a JSON column or string as a text data type. It allows you to specify a path of keys to navigate through nested JSON objects, returning the final value found at that path. If the path does not exist or the value is not a scalar, the function returns NULL.

What You'll Need

  • A PostgreSQL database instance.
  • A table containing a column with the json data type (note: this function is specifically for the json type, not jsonb).
  • Basic knowledge of SQL SELECT statements.

Step-by-Step

  1. Identify your JSON structure: Before writing the query, examine the JSON object to determine the exact hierarchy of keys. For example, if your JSON looks like , your path is user → profile → name .
  2. Construct the basic SELECT statement: Start your query by selecting from the table where your JSON data is stored. SELECT * FROM users;
  3. Apply the function: Use json_extract_path_text by passing the column name first, followed by the keys of the path as subsequent text arguments. SELECT json_extract_path_text(data_column, 'user', 'profile', 'name') FROM users;
  4. Alias the result: Because the function name is long, use the AS keyword to give your resulting column a readable name. SELECT json_extract_path_text(data_column, 'user', 'profile', 'name') AS user_name FROM users;
  5. Filter based on the extracted value: You can use the function within a WHERE clause to filter rows based on a specific value inside the JSON. SELECT * FROM users WHERE json_extract_path_text(data_column, 'user', 'profile', 'name') = 'Jane Doe';

Common Mistakes

  • Using it on JSONB columns: This function is designed for the json data type. If you are using jsonb, you should use the #>> operator or jsonb_extract_path_text instead. Attempting to use it on jsonb will result in a type mismatch error.
  • Incorrect Path Order: The keys must be provided in the exact order they appear in the hierarchy. Providing 'name', 'profile', 'user' instead of 'user', 'profile', 'name' will return NULL.
  • Case Sensitivity: JSON keys are case-sensitive. If your key is "UserName" and you search for 'username', the function will not find the value.
  • Expecting an Array: This function is intended for extracting a single text value. If the path leads to a JSON array or a nested object rather than a string/number, the result may not be what you expect or may return the raw JSON representation as text.

Tips

  • Handling NULLs: Since the function returns NULL if a path is missing, wrap the function in COALESCE() to provide a default value. SELECT COALESCE(json_extract_path_text(data, 'city'), 'Unknown') FROM addresses;
  • Performance: Extracting paths from json columns during a WHERE clause can be slow on large datasets because it requires a full table scan. If you perform this operation frequently, consider converting the column to jsonb and creating a GIN index.
  • Comparison to Operators: While json_extract_path_text is explicit and readable, the #>> operator is a shorter shorthand for the same operation. For example, data #>> '{user,profile,name}' achieves the same result.

Troubleshooting

If your query is not returning the expected results, try these steps in order:

  1. Verify the Data Type: Run \d table_name in psql or check your table definition. If the column is jsonb, switch to jsonb_extract_path_text.
  2. Test the Path Incrementally: If a deep path returns NULL, test the first level first. If json_extract_path_text(data, 'user') returns data but json_extract_path_text(data, 'user', 'profile') does not, the error is in the second key.
  3. Check for Hidden Whitespace: Ensure there are no leading or trailing spaces in your JSON keys. A key named " name" is different from "name".
  4. Validate JSON Syntax: Ensure the data in the column is valid JSON. If the JSON is malformed, the function will throw an error rather than returning NULL.

Frequently Asked Questions

What is the difference between json_extract_path and json_extract_path_text?

json_extract_path returns the result as a json object, meaning strings will still have double quotes around them. json_extract_path_text returns the result as a standard PostgreSQL text type, removing the JSON quotes.

Can I use this function to extract elements from a JSON array?

No, json_extract_path_text is designed for navigating objects (key-value pairs). To extract elements from an array, you should use functions like json_array_elements or the #> operator with an integer index.

Does this function support wildcards?

No, the function requires exact matches for the keys provided in the path. You cannot use % or other wildcards within the path arguments.

Is it better to use this function or the #>> operator?

Both perform the same action. The function is often preferred in complex scripts or when using tools that do not handle special characters like # or > well. The operator is preferred by developers for brevity.

Will this function crash my database if the JSON is too large?

It will not crash the database, but extracting data from very large JSON blobs in a loop or a large SELECT statement can consume significant CPU and memory. For very large documents, jsonb is highly recommended for better performance.