I have a JSON file and I'm injecting the data into an HTML page. I would like to filter out any empty object array that's coming back from the JSON file.
My code is below - should I use GREP maybe?
$(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.
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.
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?)
According to JSONLint , your JSON is not valid.
The empty objects in your JSON should be like this:
{" ": ""}
Changing both empty objects to the form above makes your string valid JSON and this should parse.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.