0

This question, this one, and similar ones did not help.

The JSON below is valid.

However, invoking JSON.parse throws an error.

How can you parse valid JSON from a textarea element?

JSfiddle: https://jsfiddle.net/6gpdL81e/

let text = document.getElementById("testBox").value;
let jsonObject = JSON.parse(text);
<textarea id="testBox">
    
      {
      "name": "Foobar",
      "favorite_pets": ["capybara", "lizard"],
      "favorite_fruits": ["avocado"],
      "address": {
       "city": "FairyVille",
       "street": "42 Main St."
      }
    }
    
    </textarea>

3
  • It's having an issue with some of your whitespace characters. Commented Feb 8, 2021 at 23:21
  • What do you recommend as a solution? Users upload text like this, so we need some automated mechanism to scrub the text. Just remove all leading/trailing whitespace? Commented Feb 8, 2021 at 23:32
  • You could $('#testBox').val().replace(/[^!-~]/g, ''); to effectively remove all characters that fall outside of the char range 33-126, but really I wouldn't clean it and would just return an error to the user if the parse fails. Because there could legitimately be a valid parse error that you are going to have to handle. Commented Feb 8, 2021 at 23:36

1 Answer 1

1

It because jQuery using non-breaking space nbsp or charcode \xA0 not normal space. you need to replace it.

let text = $('#testBox').val();
let jsonObject;
try {
  jsonObject = JSON.parse(text);
} catch (ex) {
  console.log("error: ", ex.message)
}
text = text.replace(/\xA0/g, " "); // or \s but will also replace newline
jsonObject = JSON.parse(text);
console.log("what the name: ", jsonObject.name)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea id="testBox">
  {
  "name": "Foobar",
  "favorite_pets": ["capybara", "lizard"],
  "favorite_fruits": ["avocado"],
  "address": {
   "city": "FairyVille",
   "street": "42 Main St."
  }
}

</textarea>

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.