softwareplay
softwareplay

Reputation: 1409

Json list to javascript object to build a form

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({&quot;Form&quot;: [{&quot;Name&quot;:&quot;Conan&quot;

I'm doing something silly, i'm sure, but i have to make it work.

Upvotes: 4

Views: 3995

Answers (3)

Yabada
Yabada

Reputation: 1758

I would do it this way :

Make an ajax call to fill var data with json.

var data = '{"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"}]}';
var obj = [];
$.each(data.Form, function(key,value) {
   var tmpObj = {};
   $.each(value, function(key2,value2){
       tmpObj[key2] = value2;
   });     
   obj.push(tmpObj);
});

This way you can use obj when you need to like this :

obj[0].Name // Conan
obj[0].Value // Children Movie
obj[1].Description // Adventure

Upvotes: 0

quoo
quoo

Reputation: 6307

I think the problem is the &quot; in your JSON string which would make it invalid.

If you do a jsonString.replace(/&quot;/g,'"'); to replace all the &quot;'s with real quotes.

See this js fiddle for an example.

Upvotes: 1

Johan
Johan

Reputation: 35194

Since you tagged it with jQuery, why not do something like this (assuming you want the items represented as radiobuttons):

To fetch the json file using $.ajax:

$.ajax({
    url: 'file.json',
    dataType: 'json',
    success: function(data){
        //manipulate the parsed json here ('data')
    }
});

'Hard coded' example without the ajax call:

var objectFromJson = $.parseJSON('{"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"}]}');

$(function(){

    $.each(objectFromJson.Form, function(k, v){

        var $radio = $('<input/>')
                        .prop({ type: 'radio', id: v.Name, name: 'form' })
                        .val(v.Value),
            $label = $('<label />')
                        .prop({ 'for': v.Name })
                        .text(v.Name)
                        .prepend($radio);

        $('form[action="/myform/"]').append($label);
    });

});

Fiddle

Upvotes: 3

Related Questions