如何将文本从 div 解析为 JSON?



主要思想是从div中获取文本并将其放入json对象中。 https://jsfiddle.net/4rqo1szm/1/如果我在 javascript 部分中声明 json 对象,我可以做我想做的事情,但我不能只是从div 中获取 text(( 并进行相同的操作。我注释掉了我想要实现的目标。

.HTML:

<div class="test"></div>
<div class="basicDiv" style="visibility: hidden;">{
"msg"   : "apple",
"otherInfo" : "v1"
},
{ 
"msg"   : "orange",
"otherInfo" : "v2"
},
{
"msg"   : "pineapple",
"otherInfo" : "v3"
}</div>

爪哇语

//var json = JSON.stringify($(".basicDiv").text());
var json = [
{
"msg"   : "apple",
"otherInfo" : "v1"
},
{
"msg"   : "orange",
"otherInfo" : "v2"
},
{
"msg"   : "pineapple",
"otherInfo" : "v3"
}
] // I'd like to remove that part
var result = json.map(function(val) {
return val.msg;
}).join(', ');

$(".test").html(result);

欢迎任何建议。并感谢大家的帮助!

div 文本中缺少"["和"]"。

try{
var json = JSON.parse("["+$(".basicDiv").text()+"]");
}catch(err){
console.log('Invalid JSON format')
}

并且,对于解析 JSON 文本,请使用JSON.parse(jsonText)而不是JSON.stringify(jsonText)

最新更新