javascript - 无法使用 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>
解决方案
这是因为 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>
推荐阅读
- postgresql - Will making column nullable lock the table for reads?
- java - 无法在列表视图中填充我的所有应用
- reactjs - 如何制作/编辑弹出表单组件
- c# - 具有 XML 布局的 Excel 自定义任务窗格
- kubernetes - k8s 仪表板中的 Argo Workflow Engine 实体
- node.js - 是否有关于使用自适应卡的自定义提示的文档?
- angular6 - ngForm simple example in angular 6 with select box
- java - 从字符串中删除以特殊字符开头和结尾的文本
- sql - Db2 Warehouse MDC 外键关系
- python - 如何在python中的3D数组内绘制2D数组