[英]jQuery GREP + JSON empty data filter
I have a JSON file and I'm injecting the data into an HTML page. 我有一个JSON文件,正在将数据注入HTML页面。 I would like to filter out any empty object array that's coming back from the JSON file.
我想过滤掉从JSON文件返回的所有空对象数组。
My code is below - should I use GREP maybe? 我的代码如下-应该使用GREP吗?
$(data.content).each(function(index, content){
$("#htmlID").append('<span>' + content.myinfo + ');
});
{
"content":
[
{"myinfo":"Bill Clinton 095 years old. "},
{" "},
{"myinfo":"Bill Clinton 295 years old. "},
{" "}
]
}
Can't you just ignore empty data? 您不能只忽略空数据吗? Something like this?
像这样吗
$(data.content).each(function(index, content){
if(!(typeof content.myinfo === "undefined" ||
content.myinfo.length<1)){
$("#htmlID").append('<span>' + content.myinfo);
}
});
A part from the {" "} syntax error (was it meant to be just '{}'?) the only proper way to do this is using a parser to iterate the object and remove what's not needed. 属于{“”}语法错误的一部分(这意味着只是'{}'吗?),执行此操作的唯一正确方法是使用解析器来迭代对象并删除不需要的对象。
This could be done using jQuery.parseJSON( json )
(see: http://api.jquery.com/jQuery.parseJSON/ ) that also ensures there is no malicious code that gets executed in the JSON string. 这可以使用
jQuery.parseJSON( json )
(请参阅: http : //api.jquery.com/jQuery.parseJSON/ )完成,该方法还可以确保在JSON字符串中没有执行恶意代码。
Other ways, such as removing lines matching a regexp, are just quite bad hacks that could lead to many problems in some non-standard scenarios. 其他方法(例如删除与正则表达式匹配的行)只是非常糟糕的黑客行为,在某些非标准情况下可能导致许多问题。
EDIT: I see there's also this: http://code.google.com/p/jquery-json/ to convert back the JS object into a JSON string. 编辑:我也看到了这个: http : //code.google.com/p/jquery-json/将JS对象转换回JSON字符串。
Anyways, I'm not sure about what your actual need is (what's inside content.myinfo
? why are you building that HTML+JSON code that way? How is the JSON string generated?) 无论如何,我不确定您的实际需求是什么(
content.myinfo
里面有什么?为什么要以这种方式构建HTML + JSON代码?JSON字符串是如何生成的?)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.