2012-06-18 25 views
68

Tengo un objeto JSON en formato de abajo:Cómo crear objeto JSON usando jQuery

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

¿Cómo puedo crear el objeto JSON en jQuery para el formato anterior. Quiero crear un objeto JSON dinámico.

Respuesta

25

Un "objeto JSON" no tiene sentido: JSON es un formato de intercambio basado en la estructura de la declaración del objeto Javascript.

Si desea convertir su objeto javascript en una cadena json, use JSON.stringify(yourObject);

Si desea crear un objeto de JavaScript, simplemente lo hacen así:

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

@guillaumealgis, ¿puede explicar su rollo de nuevo a mi edición? Si ejecuta el objeto a través de [JSONLint] (http://jsonlint.com/), se marcará como no válido (las teclas de la izquierda deben estar doblemente citadas). No estoy argumentando que estás equivocado, quiero aprender por qué crees que es JSON válido porque puede ser algo que no entiendo. Si ejecuta mi versión a través del mismo validador, vuelve como JSON válido. – delliottg

+1

@delliottg No utilice un validador JSON para validar JavaScript. Por favor, lea el comienzo de mi respuesta nuevamente. –

+2

@delliottg No estoy diciendo que sea un JSON válido. El objetivo de esta respuesta es diferenciar JSON un objeto JS. Intenta ejecutar el código dystroy en un intérprete JS y verás que funciona perfectamente. –

177

sólo hay que poner sus datos en un objeto como éste:

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

Después stringify vía:

var myString = JSON.stringify(myObject); 

No necesita jQuery para esto. Es puro JS.

+2

¿Es posible crear un nombre de índice de forma dinámica? por ejemplo: var name = $ ('# myname').val(); myObject.name = "john" // aquí el índice del nombre será dinámico desde un cuadro de entrada. –

+3

Un bache para el comentario anterior: para reemplazar cualquiera de los valores estáticos, como '.name'' .age' o '.pets', simplemente reemplace eso, incluido el punto, con una variable entre corchetes. Ejemplo: 'myObject [cssProp] = cssVal;' Entonces cualquiera que sean los valores de esas dos variables css se usará en el Objeto. Aquí está un jsFiddle: [http://fiddle.jshell.net/arttronics/rucjtbza/](http://fiddle.jshell.net/arttronics/rucjtbza/) – arttronics

4

Creo que está pidiendo escribir el nuevo JSON en un directorio. Necesitará algunos Javascript y PHP. Así que, para el de lengüeta de las otras respuestas:

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 
?> 
-1
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) { 

         } 
        }); 
+0

Eso es bueno, pero la pregunta no involucra C# o ASP – Machavity

+0

@Machavity, ¿dónde encuentras C# en esto? –

+1

Ese comentario fue sobre la primera revisión de su respuesta, que tenía C# en ella. Ahora tiene aún menos sentido, ya que está codificando la variable 'modelo'. Esta pregunta es: _ "En JavaScript, cómo puedo crear un objeto en tiempo de ejecución y representar ese objeto en notación JSON" _, cuya respuesta aún no se muestra. – CodeCaster

0

anidada JSON objeto

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

Puede analizar esto data.view.type y data.view.note

JSON objeto y matriz dentro

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

puede analizar esta data.view[0].type y data.view[0].note