skip to Main Content

I have a variable str

let str = '{"id": "option2", "text": ""hello world""}';

when i try to convert to json using JSON.parse(str);, it throws an error SyntaxError: Expected ',' or '}' after property value in JSON at position 28. I’m aware that the javascript engine reads the str as

{"id": "option2", "text": ""hello world""}, so it’s expecting a , or a } after the first set of double quotes ("") that appear before hello world.

Putting an extra backslash allows JSON.parse(str); to run.

let str = '{"id": "option2", "text": "\"hello world\""}';

However, I’d like to put the extra backslash programatically. I’ve tried using the replace method. It doesn’t seem to have any effect

let str = '{"id": "option2", "text": ""hello world""}'.replace(/\"/g, '\\"');

JSON.parse(str) still throws the same error.

The result i’m looking for is such that when str.text is printed on the console, it’s value should be "hello world"

2

Answers


  1. You need to use " if you want to KEEP the quotes

    let str = `{"id": "option2", "text": ""hello world""}`;
    let obj = JSON.parse(str);
    document.getElementById("output").innerHTML = obj.text
    <span id="output"></span>
    Login or Signup to reply.
  2. the chalenge is that the beginning quoted words are differ from the end. And it seems like javascript has some bugs and doesn’t allow to replace "/" using replace function. So only this code works for me

    let sourceStr = '{"id": "option2", "text": ""hello world""}';
    const searchStr = '""';
    
    const indexes = [...sourceStr.matchAll(new RegExp(searchStr, "gi"))].map(
      (a) => a.index
    );
    console.log(indexes); // [26,39]
    
    var sourceStrFixed = "";
    var index;
    for (index = 0; index < indexes.length; index += 2) {
      sourceStrFixed +=
        sourceStr.substring(0, indexes[index]) + '"\"'
        + sourceStr.substring(indexes[index] + 2, indexes[index + 1]) + '\""';
    }
    sourceStrFixed += sourceStr.substring(indexes[index - 1] + 2);
    console.log(sourceStrFixed);
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search