Javascript/jQuery newbie here.
My webserver is sending the contents of a directory tree as a JSON object. The object is arbitrarily nested depending on the number of subdirectories containing other subdirectories. It looks like this:
{
"contents": [
{
"filename": "myfile",
"mtime": 123456,
"size": 2345,
"content": nil
},
{
"filename": "mydir",
"mtime": 2345678,
"size": 3456788,
"content": [
{...},
{...}
]
}
]
}
myfile is a normal file and so “content” is empty. mydir is a directory which may be empty, or contain other files or subdirectories.
I want to parse this JSON with javascript and generate an html ul representation of the contents. My question is: Is there an easy/recommended way to do this?
If you’re receiving the JSON text via an ajax call using jQuery, jQuery will deserialize it into an object graph for you. If you’ve received it in some other way and have it in a string, you can deserialize it with
jQuery.parseJSON.However, the JSON you’ve quoted is invalid, specifically this bit:
There is no
nilkeyword in JSON. You’ll want to fix the server to either leave the key off entirely, or usenull, or something else. Valid JSON is defined on the JSON website, and you can use http://jsonlint.com for handy validation (and formatting). It might also be useful to usecontentorcontentsconsistently; currently the top level usescontentsbut the subordinate entries usecontent.Once you have the object graph, it’s a fairly simple matter of a recursive function, looping through the array entries and, for entries that can have nested content, calling itself again to loop through that. Something vaguely like this (live copy):