i'm not sure about how JSON's lists work when parsed as javascript objects. But however i'm niether used to javascript, so my question and the proposed solution could contain stupid mistakes. I have a JSON file, and i have to build a form from it, so i'm parsing it with jQuery .parseJSON to obtain a javascript object. The json file is the following:
{"Form": [{"Name":"Conan",
"Description":"Adventure",
"Value":"Children Movie"},
{"Name":"Sandocan",
"Description":"Adventure",
"Value":"Children Movie"},
{"Name":"Terminator",
"Description":"Sci-Fi",
"Value":"Action Movie"},
{"Name":"Iron Man",
"Description":"Adventure",
"Value":"Children Movie"}]}
It should be right from the syntax point of view.
The code tha processes it is in a web page, the JSON code is printed in the page by a template tag: {{line}}. I tried assigning it to a variable but i'm still not sure if the code really processes it. However the code of the page is below:
<html><script src="../jquery.js">
</script>
<body><p> Data previously inserted: {{line}}</p>
<form action="/myform/" method="post">Choose the movie you prefer:<br />
<script language=javascript>
var lin={{line}}
var obj=jQuery.parseJSON(lin);
function str_to_obj(o){
document.write("Hello world");
for(item in o.Form) {
document.write(item.Name);
};
}
str_to_obj(obj);
</script>
<input type="radio" name="title"><br />
<input type="text" name="description"><br />
<input type="submit" value="Submit">
</form></body></html>
Firebug reports:
SyntaxError: invalid property id
var obj=jQuery.parseJSON({"Form": [{"Name":"Conan"
I'm doing something silly, i'm sure, but i have to make it work.
Django? You can't directly put var lin = {{ line }} in a JavaScript file/script, it won't be interpreted properly as you can see with the""".forloop theitemvariable will actually be the index, not the item itself so you needo.Form[item].Name. (But you shouldn't use afor..inloop on an array, you should use a conventionalfor(var i=0;i<o.Form.length;i++){document.write(o.Form[i].Name);}.)