Remove double quote in json_encode()

Remove double quote in json_encode()

  1. Blog
  2. 15 November 2026
  3. 4 min read

Stefan Bogdanescu

Founder & Senior Architect

Remove double quote in json_encode()

You are attempting to serialize a PHP array directly into JSON, but you've encountered a specific formatting requirement: you need to output keys without surrounding quotes while keeping the values quoted. Your current approach uses json_encode() followed by a preg_replace regex to strip the opening quotes from the keys. While this works for simple cases, it introduces significant fragility and potential security risks into your codebase.

The core issue lies in how JSON syntax defines objects. According to the RFC 8259 standard, object member names (keys) must be strings enclosed in double quotes. Your desired output:

[{id_posiciones:"1",posicion:"1",...}]

is not valid JSON. If a consumer tries to parse this response using any standard JSON parser (like json_decode in PHP, JSON.parse in JavaScript, or libraries in Python), it will throw a syntax error. The lack of quotes around keys makes the string unparseable by machines.

Why Regex is the Wrong Tool Here

Your current solution attempts to fix this post-encoding using:

$array_final = preg_replace('/"([a-zA-Z]+[a-zA-Z0-9]*)":/','$1:',$array_final);

This regex matches a double quote, captures the key name, and replaces the sequence with just the key name followed by a colon. While it might produce the visual appearance you want, it breaks the data structure. You are manually constructing invalid JSON to satisfy a specific display requirement rather than using a valid format.

If you need to send this data to a frontend application (especially if that frontend is written in JavaScript), standard parsers will fail immediately. Even if you are sending this raw string to a legacy system that expects non-standard JSON, relying on regex for structural modification is brittle. It fails with keys containing special characters, numbers at the start of keys, or when the value itself contains quotes that interact unexpectedly with the pattern.

The Modern Solution: Native Language Features

The most robust way to achieve your goal today without breaking valid JSON syntax is to leverage native PHP features designed for this purpose. If you are working with Laravel (common in modern web stacks), the JsonSerializable interface or specific encoding options handle this cleanly.

However, looking at your source code, you are using the legacy mysql_* functions and json_encode. These indicate an older codebase. To fix this without rewriting the entire data layer, you have two safe paths:

  1. Use JSON_PRETTY_PRINT or Custom Options (PHP 5.4+):
    Standard json_encode always quotes keys. There is no flag to unquote them because it violates the spec. You cannot change this behavior via flags.

  2. Switch to PDO and Prepared Statements:
    Your current code concatenates user input ($params['pos_ini']) directly into a SQL query:

    $result = mysql_query("SELECT * from ranking WHERE posicion BETWEEN     ".$params['pos_ini']." AND ".$params['pos_fi']) or die('Could not query');
    

    This is vulnerable to SQL injection. Even if you fix the JSON issue, this logic remains dangerous. Migrating to PDO or MySQLi with prepared statements is a mandatory step for any production application.

Handling Non-Standard Output

If your requirement is strictly to output non-standard JSON (keys without quotes) for display purposes only, and you cannot change the consumer side of the API, you must accept that json_encode alone won't do it. You have to construct the string manually or use a library that supports custom formatting, though standard libraries enforce valid JSON by default.

If you are open to upgrading your stack, moving from the deprecated mysql_* functions to PDO is highly recommended. In modern Laravel applications, you would typically interact with Eloquent models or a repository pattern where data serialization is handled automatically and safely.

For example, in a modern context, you might use JsonSerializable to define custom output formats if your framework supports it, but for raw PHP, the trade-off is clear: you either stick to valid JSON (which requires quote-escaped keys) or manually build the string. Manually building the string loses type safety and increases the chance of syntax errors if a value contains a comma or parenthesis that needs escaping.

Conclusion on Implementation

If you must output that exact non-standard format, your regex approach is technically functional for simple alphanumeric keys but should be replaced with a manual string builder loop to ensure safety:

$output = '[';
foreach ($array_json as $item) {
    $output .= '{';
    $keys = array_keys($item);
    foreach ($keys as $keyIndex => $key) {
        // Remove quotes from key for display, but keep value safe
        $safeKey = str_replace('"', '', $key); 
        $value = $item[$key];
        
        if ($keyIndex > 0) {
            $output .= ',';
        }
        $output .= "$safeKey:$value";
    }
    $output .= '}';
}
$output .= ']';
echo $output;

This approach gives you explicit control over the output format without relying on fragile regex patterns, though it still produces invalid JSON. Always weigh the benefit of a custom display format against the cost of breaking standard parsers.

Our network