Skip to content

FIELD NOTES / A DECISION GUIDE

How to Decode and Format JSON Stored as an Escaped API String

On this page
AI-generated illustration; not taken on location · Conceptual workflow from response text to an inspected field, conditional decoding and formatted output.
AI-generated illustration; not taken on location · Parse the outer response once, inspect the field, and decode it only when its type and documented meaning justify parsing.AI-generated illustration

To decode JSON stored inside an API string, first parse the outer response, then inspect the selected field. If that field is a string and the API contract defines its contents as serialized JSON, parse the field separately. Finally, format the resulting value for inspection. Do not remove backslashes to make the response look cleaner: they can preserve quotation marks, literal backslashes, and control characters.

The central question is what the field means, not how many backslashes appear on screen. An API may return a nested object, ordinary text, or text containing another JSON document. Those cases call for different handling, even when a response viewer makes them look similar.

The constructed examples below follow a field named payload through each step. They distinguish the response text, the parsed response, the selected field, and readable output. Use that same sequence before taking a value to FormatBits’ JSON formatter: identify the layer, decode only where justified, and format the value you actually want to inspect.

Identify the layer you are inspecting

JSON is a text format for representing structured data. When an API response contains JSON text inside one of its strings, you are working with two separate serialization boundaries. Start by naming the layer in front of you.

Layer What to establish Next action
Raw response text Has the outer document been parsed? Parse the response once.
Parsed response value What does the selected field contain? Inspect its type and documented meaning.
Debugger or viewer display How is the tool rendering that value? Check the value itself before transforming it.

Compare these two constructed response documents:

{"payload":{"item":"map","count":2}}
{"payload":"{\"item\":\"map\",\"count\":2}"}

In the first document, payload contains an object. In the second, it contains a string whose contents represent an object. Parsing the outer response gets you to the selected field; only the second example calls for another parse, assuming that interpretation matches the API contract.

After outer parsing, inspect the field directly:

const field = outer.payload;

console.log(typeof field);
console.log(field);

Treat visible backslashes as a reason to investigate the representation, rather than as a decoding instruction. Ask whether you copied the actual response body, a string literal from source code, or a viewer’s representation of a string. Keep one small sample and label its layer so that later comparisons refer to the same value.

Parse the outer response once

Choose the entry point that matches the input you already have. For a Fetch response, the supplied workflow uses response.json() to obtain the response as JSON:

async function readPayload(response) {
  const outer = await response.json();
  return outer.payload;
}

If the response body is already available as text, use that text as the input to JSON.parse():

function readPayloadFromText(rawText) {
  const outer = JSON.parse(rawText);
  return outer.payload;
}

These are alternative entry points. Select one according to whether your starting value is a response or response text. If a client library has already supplied the parsed response, begin with that value and inspect the field directly.

Mark where outer parsing ends

At the end of either example, you have selected payload; you have not established that it needs decoding. With the object-containing response from the previous section, the selected field is already the intended object. With the string-containing response, the selected field is still text.

Before moving on, answer two questions: has the outer response already been parsed, and does the API document the expected response structure? The examples here assume an outer object with a payload property. If your API specifies a different structure, adapt the field selection to that contract.

Keep outer parsing and field interpretation as distinct steps in your code. That separation makes the next decision reviewable and helps you identify which input caused a failure.

Decode only a field intended to contain JSON

A string type alone does not justify another parse. A message, title, or identifier can be ordinary text even when its contents resemble JSON. Establish the field’s documented meaning first, then use its runtime type to select the operation.

The following helper illustrates a policy choice: preserve existing values, and parse strings only when the caller has established that the field is intended to contain JSON text.

function decodeSelectedField(field, containsJsonText) {
  if (!containsJsonText || typeof field !== "string") {
    return field;
  }

  return JSON.parse(field);
}

The containsJsonText argument should reflect the API contract or an explicit configuration based on that contract. Do not derive it merely from a leading brace, visible escaping, or a successful experimental parse. The helper also does not validate whether a preserved value meets the API’s requirements; perform that check separately.

Decide what decoded results are acceptable

A valid JSON document can contain a primitive value, and arrays can also be converted to and from JSON. Successful parsing therefore does not establish that your result is the object your application expects.

For a hypothetical field that must decode to an object excluding arrays and null, an explicit check could be:

const decoded = decodeSelectedField(field, containsJsonText);

if (
  decoded === null ||
  Array.isArray(decoded) ||
  typeof decoded !== "object"
) {
  throw new Error("Expected an object payload");
}

Use that restriction only if it matches your contract. If arrays, null, strings, numbers, or booleans are allowed results, define the corresponding acceptance rules. Keep the questions separate: should this field be parsed, and is the resulting value acceptable?

Why removing backslashes corrupts data

Escapes carry information inside JSON strings. Quotation marks, backslashes, and control characters require escape sequences; literal newline and tab characters are invalid inside JSON strings. Deleting the escape markers can change the intended value or leave invalid JSON.

Consider this constructed JSON document:

{
  "quote": "She said \"go\".",
  "path": "folder\\notes",
  "message": "first\nsecond"
}

Each field demonstrates a different reason to preserve the serialized text until parsing:

Field Intended value after parsing Effect of deleting backslashes from the JSON text
quote Text containing quotation marks around go The interior quotes lose their escaping, breaking the string syntax.
path folder, a literal backslash, then notes The separator disappears, changing the value to foldernotes.
message first, a newline, then second The newline escape becomes the letter n, producing firstnsecond.

These outcomes follow different failure paths: one damages syntax, while the others can produce altered text that still looks plausible. A successful syntax check after replacement would therefore not prove that the original content survived.

Preserve the intended characters

If this entire document is stored inside an outer response string, let outer parsing recover the inner JSON text. Then, when the contract calls for it, parse that inner text. Each parse handles the escapes belonging to its own serialization layer.

For troubleshooting, choose a small sample containing meaningful quotation marks, a literal backslash, and an escaped newline. Compare the resulting values with the intended content. A display with fewer backslashes is not, by itself, evidence of a correct conversion.

Format the decoded value for inspection

Parsing and formatting serve different purposes. Parsing converts JSON text into a usable value. Formatting serializes a value as readable JSON text. Once you have selected and, where appropriate, decoded the field, create readable output with:

const formatted = JSON.stringify(decoded, null, 2);
console.log(formatted);

This example requests two-space indentation. Apply it to the value you mean to inspect. Formatting the entire outer response does not perform the separate field-decoding decision.

For example, an outer response containing serialized field content may format as:

{
  "payload": "{\"item\":\"map\",\"count\":2}"
}

The indentation makes the outer structure easier to read, while payload remains a string. If the contract identifies that string as JSON text, decoding the field and then formatting its value produces:

{
  "item": "map",
  "count": 2
}

Choose the right input for FormatBits

Use FormatBits’ JSON formatter at the inspection stage, with the JSON text corresponding to the layer you want to examine. For the decoded field above, that means its serialized object representation. This workflow does not assume that the formatter automatically discovers or decodes nested JSON strings.

Keep syntax checking separate from checking the API’s expected structure. Readable, valid JSON still needs comparison with the documented field names, required values, and accepted result types. Ask both whether the text can be parsed and whether the resulting value is appropriate for the application. Formatting supports that inspection; it does not settle the contract question.

Handle failures at the correct boundary

Keep failures associated with the operation that encountered them. A malformed outer response, invalid JSON text inside a selected field, and an unacceptable decoded type need different investigations.

Boundary What to inspect next
Outer response parsing The original response text and expected outer structure.
Selected field parsing The field’s actual text and the contract identifying it as JSON.
Decoded value validation The accepted types and structure for that field.

Separate parsing blocks make the distinction explicit:

let outer;
try {
  outer = JSON.parse(rawText);
} catch {
  throw new Error("Outer response is not valid JSON");
}

const field = outer.payload;
let decoded = field;

if (containsJsonText && typeof field === "string") {
  try {
    decoded = JSON.parse(field);
  } catch {
    throw new Error("Payload is not valid JSON text");
  }
}

// Apply the documented result-type and structure checks here.

This constructed example assumes that the outer structure has been checked before selecting payload. In application code, include that check at the appropriate boundary as well.

Resolve ambiguity through the contract

If the documentation does not say whether a field is plain text or serialized JSON, ask the API owner which interpretation consumers should use. Also ask what type should remain after decoding. Repeatedly parsing strings until an attempt fails substitutes trial and error for those decisions and can obscure the layer that actually needs attention.

Before applying the workflow to unfamiliar data, clarify whether large numbers or duplicate property names must be preserved beyond ordinary JavaScript object parsing. If they matter, obtain explicit handling requirements rather than assuming this example meets them.

Finally, confirm whether the input contains one JSON document or a separately framed sequence. A JSON text sequence is not itself a single JSON text; obtain its framing requirements before choosing how to process it. Finish with a known boundary, an accepted value, and readable output whose meaningful characters have been preserved.