我有一个读取文本区域输入的函数。
文本区域的输入以字符串形式返回,但我希望它是一个对象。
如何把它变成一个对象?我使用了 json.parse 和 eval。我收到错误: VM16897:1 Uncaught SyntaxError: JSON 中位置 0 的意外标记 v 在 JSON.parse()
我想要的格式:
var a = {
"ss": [{
"name": "O",
"id": "shh1",
"url": "hthh.sss"
}]
}],
"Maacks": [{
"name": "Default",
}
}]
}
当我得到 textarea 输入时我得到了什么:
"var a = {
"ss": [{
"name": "O",
"id": "shh1",
"url": "hthh.sss"
}]
}],
"Maacks": [{
"name": "Default",
}
}]
}"
最佳答案
您应该像下面这样输入,不带 var a =
。此外,您还必须纠正左括号和右括号。
{
"ss": [{
"name": "O",
"id": "shh1",
"url": "hthh.sss"
}
],
"Maacks": [{
"name": "Default"
}
]
}
然后使用 JSON.parse
解析,如下所示,
var a = JSON.parse(textArea.value);
工作样本
// Copy the below content inside the commented line (/* ... */) into the text area and click the 'Convert' button,
/*
{
"ss": [{
"name": "O",
"id": "shh1",
"url": "hthh.sss"
}
],
"Maacks": [{
"name": "Default"
}
]
}
*/
function convert() {
var jsonText = document.getElementById('textArea').value;
if(jsonText) {
try {
var json = JSON.parse(jsonText);
console.log(json);
} catch(e) {
console.log(e);
}
}
}
<textarea id="textArea" rows="10" cols="50"></textarea>
<br/>
<input type="button" value="Convert" onclick="convert()"/>
关于javascript - 将文本区域输入字符串转换为类型对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40600577/