1

I am trying to create a function that parses JSON text.

function JSONParser(string) {
  //CODE HERE
  string = string.replace(/"/g, "");

  var obj = {};
  obj[0] = string;
  string = obj[0].replace(/'/g, "");

  return string;
}

I only did the funky thing with the object because .replace didn't seem to work directly on the string the second time.

When I run this code through a checker. I get...

JSONParser(JSON.stringify(true));
"true"

I am aiming to return the boolean true and not a string.

Does anyone know why I still get a return with double quotes? Is there more to changing a string object than removing the quotes? Or, am I simply trying to remove them incorrectly?

Any help would be greatly appreciated. TIA

-Lea

0

1 Answer 1

2

Because it's still a string, so the console displays it with quotes (as decoration).

Remember, when you do var foo = "true", the quotes aren't actually part of the string, so there's no need to remove them. Your console just shows them as a way to indicate the type of data it's showing. They're not actually there.

If you want a boolean, you can do something like this:

function JSONParser(string) {
  return string === "true" ? true :
         string === "false" ? false : string;
}

console.log(JSONParser(JSON.stringify(true)));

If the string is neither "true" nor "false", it just returns the original string.


If you prefer if statements, then:

function JSONParser(string) {
  if (string === "true") {
    return true;
  } else if (string === "false") {
    return false;
  } else {
    return string;
  }
}

console.log(JSONParser(JSON.stringify(true)));

Or a switch statement would be useful too.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.