代码之家  ›  专栏  ›  技术社区  ›  user469652

基于这个需求构建JSON,可以使用jQuery!!! 挑战!

  •  1
  • user469652  · 技术社区  · 15 年前

    我不知道怎么写这个JS,所以在这里寻求帮助!

    HTML格式

    <div class="grid_18" id="reference_container">
        <div class="grid_16">
            <fieldset>
                <legend>Website</legend>
    
                <span class="grid_2">Person</span>
                <input name="person" class = "grid_6" type="text" />
    
                <span class="push_2">Year</span>
                <input class="push_2" name="year" type="text" />
            </fieldset>
        </div>
    
        <div class="grid_16">
            <fieldset>
                <legend>Newspaper</legend>
    
                <span class="grid_2">Author</span>
                <input name="author" type="text" />
    
                <span class="push_4">Year</span>
                <input class="push_4" name="year" type="text" />
    
            </fieldset>
        </div>
    </div>
    

    我需要的是每个字段集一个JSON列表。结果如下:

    [
        {type:"website"     , person: "(Based on user input)", year: "(Based on user input)"},
        {type:"Newspaper", author: "(Based on user input)", year: "(Based on user input)" }
    ]
    

    (类型为静态,内容来自图例,其他字段不相同)

    需要注意的是,字段名不是静态的(person、author等),需要从name属性中提取。

    这对我来说是个挑战,希望谁能帮上忙~

    2 回复  |  直到 7 年前
        1
  •  1
  •   Andy E    15 年前

    我有一个不需要的解决方案 json2.js . 它使用jQuery的 serialize() 方法并将查询字符串字符替换为有效的JSON分隔符:

    var arr = [];
    
    $("fieldset").each(function () {
        var $this = $(this),
            serialized = $this.children("input").serialize(),
            type = $this.children("legend").text();
    
        // Replace the jQuery-serialized content into valid JSON
        serialized = serialized.replace(/([^=]+)=([^&]*)(&)?/g, function ($0, name, val, amp) {
            return '"'+name+'":'+'"'+val+'"' + (amp ? "," : "");
        });
    
        // Add it to the array
        arr.push('{"type":"'+type+'",'+serialized+'}');
    });
    
    // Join the array into a valid JSON string
    var json = "[" + arr.join(",") + "]";
    

    这里有一个工作演示: http://jsfiddle.net/AndyE/ASrKN/

    请注意,它不会对结果进行重新解码(例如,如果用户输入的字符应该是url编码的),但如果仍要发布到服务器,则可能希望这些字符保持编码。

        2
  •  2
  •   Matt user129975    15 年前
    var json = JSON.stringify($('fieldset').map(function () {
      var self = $(this);
      var obj = {
        type: self.children('legend').text()
      };
    
      // Find each input element with a name attribute, and add the name/val to the object
      self.find('input[name]').each(function () {
        obj[this.name] = this.value + " (Based on user input)";
      });
    
      // Return the object we've constructed
      return obj;
    }).get());
    

    map: 对每个匹配的元素执行提供的函数,并返回一个新的jQuery对象,其元素是每个元素的函数返回值。

    get: 将jQuery对象作为数组返回。

    请确保包含来自 https://github.com/douglascrockford/JSON-js ,以支持不包含JSON库的浏览器。