【问题标题】:How to create JSON object using jQuery如何使用 jQuery 创建 JSON 对象
【发布时间】:2012-06-18 07:11:58
【问题描述】:

我有一个以下格式的 JSON 对象:

temp:[
        {
           test:'test 1',
           testData:  [ 
                       {testName: 'do',testId:''}
                         ],
           testRcd:'value'                             
        },
        {
            test:'test 2',
           testData:  [
                            {testName: 'do1',testId:''}
                         ],
           testRcd:'value'                           
        }
      ],

如何在 jquery 中为上述格式创建 JSON 对象。我想创建一个动态 JSON 对象。

【问题讨论】:

    标签: json arrays


    【解决方案1】:

    只需将您的数据放入这样的对象中:

    var myObject = new Object();
    myObject.name = "John";
    myObject.age = 12;
    myObject.pets = ["cat", "dog"];
    

    然后通过以下方式对其进行字符串化:

    var myString = JSON.stringify(myObject);
    

    你不需要 jQuery。是纯 JS。

    【讨论】:

    • 动态创建索引名是否可行。例如: var name = $('#myname').val(); myObject.name = "john" //这里的名称索引将来自输入框。
    • 上述评论的一个亮点:要替换任何静态值,例如 .name .age.pets,只需将包括点在内的变量替换为方括号中的变量。示例:myObject[cssProp] = cssVal; 然后,无论这两个 css 变量的值是什么,都将在 Object 中使用。这是一个 jsFiddle:http://fiddle.jshell.net/arttronics/rucjtbza/
    【解决方案2】:

    “JSON 对象”没有意义:JSON 是一种基于 Javascript 对象声明结构的交换格式。

    如果要将 javascript 对象转换为 json 字符串,请使用 JSON.stringify(yourObject)

    如果你想创建一个 javascript 对象,只需这样做:

    var yourObject = {
              test:'test 1',
              testData: [ 
                    {testName: 'do',testId:''}
              ],
              testRcd:'value'   
    };
    

    【讨论】:

    • @guillaumealgis,你能解释一下你回滚到我的编辑吗?如果您通过JSONLint 运行该对象,它将被标记为无效(左键需要双引号)。我并不是说你错了,我想了解为什么你认为它是有效的 JSON,因为它可能是我不理解的东西。如果您通过相同的验证器运行我的版本,它会以有效的 JSON 形式返回。
    • @delliottg 不要使用 JSON 验证器来验证 JavaScript。请再次阅读我的答案的开头。
    • @delliottg 我并不是说它是有效的 JSON。这个答案的重点是区分 JSON 和 JS 对象。尝试在 JS 解释器中运行 dystroy 代码,你会发现它运行良好。
    • 感谢 cmets 伙计们,在再次阅读本文并就我正在从事的项目提出自己的问题后,我意识到我对这些东西的工作原理存在根本性的误解。我很确定我现在明白了,感谢您的耐心等待。
    【解决方案3】:

    我相信他要求将新的 json 写入目录。您将需要一些 Javascript PHP。所以,捎带其他答案:

    script.js

    var yourObject = {
      test:'test 1',
      testData: [ 
        {testName: 'do',testId:''}
       ],
       testRcd:'value'   
    };
    var myString = 'newData='+JSON.stringify(yourObject);  //converts json to string and prepends the POST variable name
    $.ajax({
       type: "POST",
       url: "buildJson.php", //the name and location of your php file
       data: myString,      //add the converted json string to a document.
       success: function() {alert('sucess');} //just to make sure it got to this point.
    });
    return false;  //prevents the page from reloading. this helps if you want to bind this whole process to a click event.
    

    buildJson.php

    <?php
        $file = "data.json";  //name and location of json file. if the file doesn't exist, it   will be created with this name
    
        $fh = fopen($file, 'a');  //'a' will append the data to the end of the file. there are other arguemnts for fopen that might help you a little more. google 'fopen php'.
    
        $new_data = $_POST["newData"]; //put POST data from ajax request in a variable
    
        fwrite($fh, $new_data);  //write the data with fwrite
    
        fclose($fh);  //close the dile
    ?>
    

    【讨论】:

      【解决方案4】:

      如何将输入字段值附加为 json 格式

      temp:[
              {
                 test:'test 1',
                 testData:  [ 
                             {testName: 'do',testId:''}
                               ],
                 testRcd:'value'                             
              },
              {
                  test:'test 2',
                 testData:  [
                                  {testName: 'do1',testId:''}
                               ],
                 testRcd:'value'                           
              }
            ],
      

      【讨论】:

        【解决方案5】:

        嵌套JSON对象

        var data = {
                view:{
                    type: 'success', note:'Updated successfully',
                },
            };
        

        你可以解析这个data.view.typedata.view.note

        JSON对象和数组内部

        var data = {
                  view: [ 
                        {type: 'success', note:'updated successfully'}
                  ],  
             };
        

        你可以解析这个data.view[0].typedata.view[0].note

        【讨论】:

          【解决方案6】:
          var model = {"Id": "xx", "Name":"Ravi"};
          $.ajax({    url: 'test/set',
                                  type: "POST",
                                  data: model,
                                  success: function (res) {
                                      if (res != null) {
                                          alert("done.");
                                      }
                                  },
                                  error: function (res) {
          
                                  }
                              });
          

          【讨论】:

          • 很好,但问题不涉及 C# 或 ASP
          • @Machavity,你在哪里找到c#?
          • 该评论是关于您的答案的第一个修订版,其中包含 C#。现在它变得更没有意义了,因为您正在硬编码 model 变量。这个问题是:“在 JavaScript 中,如何在运行时创建一个对象并用 JSON 表示法表示该对象”,您的答案仍然没有显示。
          猜你喜欢
          • 2013-03-19
          • 2011-10-11
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-03-01
          • 2015-08-15
          • 1970-01-01
          • 2021-04-13
          相关资源
          最近更新 更多