OpenSearch-Dashboards: [BUG] - OpenSearch Dashboard V2.15.0 - JSON.parse: bad escaped character

Describe the bug

After upgrading from 2.13 to 2.15 Discover in Dashboards is barely usable due to the following error.

SyntaxError: Bad escaped character in JSON at position 911476 (line 1 column 911477) at fetch_Fetch.fetchResponse (https://dashboards.observability-opensearch.backend.ppe.cloud/7749/bundles/core/core.entry.js:15:243032) at async interceptResponse (https://dashboards.observability-opensearch.backend.ppe.cloud/7749/bundles/core/core.entry.js:15:237932) at async https://dashboards.observability-opensearch.backend.ppe.cloud/7749/bundles/core/core.entry.js:15:240899

Related component

Search

To Reproduce

Upgrade to version 2.15.0 and it will appear in the discover.

Expected behavior

See the following error in discover

SyntaxError: Bad escaped character in JSON at position 911476 (line 1 column 911477)

Additional Details

Someone already reported this issue in OpenSearch forum https://forum.opensearch.org/t/json-parse-bad-escaped-character/20211

About this issue

  • Original URL
  • State: closed
  • Created 2 years ago
  • Reactions: 4
  • Comments: 41 (14 by maintainers)

Commits related to this issue

Most upvoted comments

We have the same issue. Any chance of fixing that in 2.17?

I believe #6915 introduced this bug. Specifically, the new dependency on the json11 node module and the call to JSON11.stringify produces JSON5 documents that are not entirely compatible with JSON.parse used elsewhere in this project.

Here’s a minimal demo of the underlying issue, using a “hello world” message with the second word wrapped in an ANSI escape code marking the color green.

Using standard JSON.stringify round-trips the original text without issue:

$ printf 'hello \u001b[38;5;2mworld\u001b[0m' |
  node -e "console.log(JSON.parse(JSON.stringify(require('fs').readFileSync(0, 'utf-8'))))"
hello world

However, using JSON11.stringify converts the ASCII escape character to \x1b (a valid JSON5 hexadecimal escape, but not valid JSON which only supports \u001b unicode escape), producing an error in JSON.parse:

$ printf 'hello \u001b[38;5;2mworld\u001b[0m' |
  node -e "console.log(JSON.parse(require('json11').stringify(require('fs').readFileSync(0, 'utf-8'), {quote: '\"'})))"
undefined:1
"hello \x1b[38;5;2mworld\x1b[0m"
        ^

SyntaxError: Bad escaped character in JSON at position 8 (line 1 column 9)
    at JSON.parse (<anonymous>)

[...]

@JannikBrand I also have been unsucessful in indexing a sample of our problematic data manually. Maybe the behaviour of the JSON Parser changes with bigger amounts of data? We are using vector in version 0.39.0 to index our log data. Vector is indexing about 10000 documents at a time using the bulk API with the create action. We have been able to work around this issue using the strip_ansi_escape_codes function of Vector (at least for new logs).

I can confirm that bumping json11 to 2.0.0 fixes the issue. I made a rebuild of 2.16.0, the error is gone.

Hi @agoerl , @JannikBrand and @Christian93. Adding a bit more details about our testing of this above bug. We tried the indexing the document that you have provided us across 2.11, 2.13 & 2.15 versions of Opensearch releases using OSD’s dev tools as well as directly hitting the Opensearch endpoints.

However we were unable to index the document. Adding the API calls that we have tried for reference below.

curl --location --request PUT 'http://localhost:9200/sample-index-2.11/_doc/1' \ --header 'Content-Type: application/json' \ --data '{ "msg": "\x1b[0mPOST /oauth/authorize \x1b[32m200\x1b[0m 95.542 ms - 1499\x1b[0m" }'

Response: {"error":{"root_cause":[{"type":"mapper_parsing_exception","reason":"failed to parse"}],"type":"mapper_parsing_exception","reason":"failed to parse","caused_by":{"type":"json_parse_exception","reason":"Unrecognized character escape 'x' (code 120)\n at [Source: (byte[])\"{\n \"msg\": \"\\x1b[0mPOST /oauth/authorize \\x1b[32m200\\x1b[0m 95.542 ms - 1499\\x1b[0m\"\n}\"; line: 2, column: 15]"}},"status":400}

Bulk APi Call: curl --location 'http://localhost:9200/_bulk' \ --header 'Content-Type: application/json' \ --data '{"index":{"_index":"test_index","_id":"1"}} {"msg": "\x1b[0mPOST /oauth/authorize \x1b[32m200\x1b[0m 95.542 ms - 1499\x1b[0m"} {"index":{"_index":"test_index","_id":"2"}} {"msg": "This is a normal message without escape sequences"} '

Response: {"took":126,"errors":true,"items":[{"index":{"_index":"test_index","_id":"1","status":400,"error":{"type":"mapper_parsing_exception","reason":"failed to parse","caused_by":{"type":"json_parse_exception","reason":"Unrecognized character escape 'x' (code 120)\n at [Source: (byte[])\"{\"msg\": \"\\x1b[0mPOST /oauth/authorize \\x1b[32m200\\x1b[0m 95.542 ms - 1499\\x1b[0m\"}\"; line: 1, column: 12]"}}}},{"index":{"_index":"test_index","_id":"2","_version":1,"result":"created","_shards":{"total":2,"successful":1,"failed":0},"_seq_no":0,"_primary_term":1,"status":201}}]}

Overall we were unable to index the document you had provided. To investigate this issue we will need your help to understand how you had indexed this document in 2.13 version or older versions and it would also be great if you can share the index mapping for the index in 2.13 version. You can use the following link https://opensearch.org/docs/latest/field-types/ to get the command for obtaining the index mapping.

Regards, cc. @ashwin-pc @ananzh

Issue

SyntaxError: Bad escaped character in JSON at position 911476 (line 1 column 911477) at fetch_Fetch.fetchResponse (https://dashboards.observability-opensearch.backend.ppe.cloud/7749/bundles/core/core.entry.js:15:243032)

Analysis

What we know now:

  • The error is not silently caught, as we see it on the browser screen.

  • It’s not from the innermost try-catch block that falls back to body = text; when JSON parsing fails.

  • The error message mentions fetch_Fetch.fetchResponse, which indicates it’s happening within this fetchResponse method.

  • Given these points, the error is likely coming from one of these two lines:

    • This is unlikely to cause a “Bad escaped character in JSON” error because it’s not parsing JSON, it’s just getting the raw blob data.
body = await response.blob();
  • The 2nd place is possible. Here, there are two possible paths: a) If withLongNumeralsSupport or withLongNumerals is true, it uses parse(await response.text()).b) Otherwise, it uses await response.json().
  fetchOptions.withLongNumeralsSupport || fetchOptions.withLongNumerals
    ? parse(await response.text())
    : await response.json();
  • This method is not updated between 2.13 and 2.15. So it is not the method that causing the isuse.
  • One more callout: The position at position 911476 and other report at 2006464 and 1618143, which are quite large. This could indicate that the issue is related to how large responses are being handled. But OSD has payload limit and we don’t see complaining about payload too large. Therefore, it should not be some truncation to cause some invalid escaped character. We need more info on this.

Reproduce

Given the limited information about the error related escaped character, the image of discover and location the catch the error, I tried to reproduce with a script which can create 500 documents with 11 fixed fields (10 specific fields plus the timestamp). The content of each field is generated using the functions that create various types of escape sequences, nested objects, arrays, number formats, etc:

"standard_escapes": Covers all standard JSON escape characters
"unicode_escapes": Includes various Unicode escape sequences (control characters, surrogate pairs, emojis)
"escaped_unicode": Incorporates escaped Unicode sequences
"double_escaped": Uses double-escaped sequences
"invalid_escapes": Includes invalid escape sequences
"long_string": Generates very long strings with mixed escapes
"nested_object": Creates nested objects with various escapes
"array_with_escapes": Produces arrays with different types of escaped content
"number_fields": Includes number fields with very large integers, high-precision decimals, and special number formats
"mixed_field": Generates mixed fields combining text, numbers, and various escapes
"potential_problem_string": Creates a string that combines many challenging elements

generate.py

import json
import random
import string
import datetime

def generate_random_string(length):
    return ''.join(random.choice(string.ascii_letters + string.digits) for _ in range(length))

def generate_long_number_as_string():
    return str(random.randint(10**50, 10**100))

def generate_random_float():
    return random.uniform(-1e100, 1e100)

def generate_all_standard_escapes():
    return json.dumps({
        "quotes": "\"Hello, World!\"",
        "backslash": "This is a backslash: \\",
        "forward_slash": "Forward slash: \/",
        "backspace": "Backspace:\b",
        "form_feed": "Form feed:\f",
        "newline": "Newline:\n",
        "carriage_return": "Carriage return:\r",
        "tab": "Tab:\t"
    })[1:-1]

def generate_unicode_escapes():
    control_chars = ''.join([f"\\u{i:04x}" for i in range(32)])
    surrogate_pairs = "\\uD83D\\uDE00"  # Smiling face emoji
    emojis = "\\u{1F600}\\u{1F64F}\\u{1F680}"  # Various emojis
    return f"{control_chars}{surrogate_pairs}{emojis}"

def generate_escaped_unicode():
    return "\\\\u00A9\\\\u00AE\\\\u2122"  # Copyright, Registered, Trademark symbols

def generate_double_escaped():
    return "\\\\\\\\u00A9\\\\\\\\n\\\\\\\\t"

def generate_invalid_escapes():
    return "\\a\\v\\0\\x\\u\\u123g"

def generate_very_long_string_with_escapes():
    base = "This is a long string with various escapes: "
    escapes = generate_all_standard_escapes() + generate_unicode_escapes()
    return base + escapes * 10

def generate_nested_object():
    return {
        "nested_escapes": generate_all_standard_escapes(),
        "nested_unicode": generate_unicode_escapes(),
        "nested_invalid": generate_invalid_escapes()
    }

def generate_array_with_escapes():
    return [
        generate_all_standard_escapes(),
        generate_unicode_escapes(),
        generate_escaped_unicode(),
        generate_invalid_escapes()
    ]

def generate_number_fields():
    return {
        "large_integer": generate_long_number_as_string(),
        "high_precision_decimal": f"{generate_random_float():.50f}",
        "special_format": f"{random.uniform(-1e100, 1e100):e}"
    }

def generate_mixed_field():
    return f"Text with number {generate_long_number_as_string()} and escapes: {generate_all_standard_escapes()}"

def generate_potential_problem_string():
    return (f"Problem string: {generate_all_standard_escapes()}{generate_unicode_escapes()}"
            f"{generate_escaped_unicode()}{generate_double_escaped()}{generate_invalid_escapes()}"
            f"{generate_long_number_as_string()}{generate_mixed_field()}")

def generate_document():
    return {
        "timestamp": datetime.datetime.now().isoformat(),
        "standard_escapes": generate_all_standard_escapes(),
        "unicode_escapes": generate_unicode_escapes(),
        "escaped_unicode": generate_escaped_unicode(),
        "double_escaped": generate_double_escaped(),
        "invalid_escapes": generate_invalid_escapes(),
        "long_string": generate_very_long_string_with_escapes(),
        "nested_object": generate_nested_object(),
        "array_with_escapes": generate_array_with_escapes(),
        "number_fields": generate_number_fields(),
        "mixed_field": generate_mixed_field(),
        "potential_problem_string": generate_potential_problem_string()
    }

# Generate and save 500 documents
documents = [generate_document() for _ in range(500)]

with open('test_documents.json', 'w') as f:
    for doc in documents:
        f.write(json.dumps({"index": {}}) + '\n')
        f.write(json.dumps(doc) + '\n')

print(f"Generated file: test_documents.json with 500 documents")
print("Use the following curl command to index these documents:")
print("curl -H 'Content-Type: application/x-ndjson' -XPOST 'localhost:9200/test_escape_index/_bulk' --data-binary '@test_documents.json'")

Then index it to 2.15 OS

curl -H 'Content-Type: application/x-ndjson' -XPOST 'localhost:9200/test_escape_index/_bulk' --data-binary '@test_documents.json'

Create index pattern using a plain 2.15 OSD. Then open in discover and all look good: Screenshot 2024-07-23 at 12 48 15 PM

Fix / Discussion

Since I can’t reproduce it, there are two ways to proceed:

  1. Adds a try-catch block specifically around the JSON parsing part. If parsing fails, it logs the error and falls back to returning the raw text of the response.This approach prevents the parsing error from breaking the application. But this might miss these errors and find out the true cause of the issue. As I mentioned earlier, this fetchResponse method is not changed between 2.13 to 2.15. We don’t what causes either parse or response.json to throw the error. If we can’t tolerate, the fix is to change
 fetchOptions.withLongNumeralsSupport || fetchOptions.withLongNumerals
    ? parse(await response.text())
    : await response.json();

to

try {
        body = fetchOptions.withLongNumeralsSupport || fetchOptions.withLongNumerals
          ? parse(await response.text())
          : await response.json();
      } catch (parseError) {
        console.error('Error parsing JSON response:', parseError);
        // Fallback to raw text
        body = await response.text();
      }
  1. Keep this open to collect more information to have a way to reproduce it.