首页 > 解决方案 > 无法使用 JSON.parse 解析来自 textarea 元素的有效 JSON

问题描述

这个问题这个问题和类似的问题都没有帮助。

下面的 JSON 是有效的。

但是,调用JSON.parse会引发错误。

如何从 textarea 元素中解析有效的 JSON?

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>

标签: javascriptjsonformsparsingtextarea

解决方案


这是因为 jQuery 使用不间断空格nbsp或 charcode\xA0不是普通空格。你需要更换它。

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>


推荐阅读