jquery - Json list to javascript object to build a form - Stack Overflow

i'm not sure about how JSON's lists work when parsed as javascript objects. But however i

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.

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.

Share Improve this question asked Jul 18, 2013 at 13:42 softwareplaysoftwareplay 1,4194 gold badges30 silver badges67 bronze badges 4
  • What template library are you using? Something like 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 "&quot;". – Ford Commented Jul 18, 2013 at 13:46
  • 2 Once you get past that problem, the next will be that inside your for loop the item variable will actually be the index, not the item itself so you need o.Form[item].Name. (But you shouldn't use a for..in loop on an array, you should use a conventional for(var i=0;i<o.Form.length;i++){document.write(o.Form[i].Name);}.) – nnnnnn Commented Jul 18, 2013 at 13:47
  • Don't show us a server side template and report a JavaScript error. Determine if the problem is that the server side code isn't outputting the code you expect or if the output code is not doing what you think it should - then focus on the relevant half. – Quentin Commented Jul 18, 2013 at 13:50
  • Also, the convention for naming keys inside of json objects is to use lowercase. But that's not that big a deal. – quoo Commented Jul 18, 2013 at 14:01
Add a ment  | 

3 Answers 3

Reset to default 3

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

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.

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

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745453385a4628372.html

相关推荐

  • jquery - Json list to javascript object to build a form - Stack Overflow

    i'm not sure about how JSON's lists work when parsed as javascript objects. But however i

    4小时前
    20

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信