Crashalot
Crashalot

Reputation: 34523

Unable to parse valid JSON from textarea element with JSON.parse

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>

Upvotes: 0

Views: 321

Answers (1)

uingtea
uingtea

Reputation: 6554

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>

Upvotes: 1

Related Questions