2012-06-18 19 views
68

Ho un oggetto JSON in seguito formato:Come creare oggetto JSON utilizzando jQuery

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

Come posso creare oggetto JSON in jQuery per il formato sopra. Voglio creare un oggetto JSON dinamico.

risposta

25

Un "oggetto JSON" non ha senso: JSON è un formato di scambio basato sulla struttura della dichiarazione di oggetto Javascript.

Se si desidera convertire l'oggetto javascript in una stringa json, utilizzare JSON.stringify(yourObject);

Se si desidera creare un oggetto JavaScript, è sufficiente fare in questo modo:

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

@guillaumealgis, puoi spiegare la tua rollback alla mia modifica? Se si esegue l'oggetto tramite [JSONLint] (http://jsonlint.com/) viene contrassegnato come non valido (i tasti a sinistra devono essere citati due volte). Non sto sostenendo che ti sbagli, voglio sapere perché credi che sia un JSON valido perché potrebbe essere qualcosa che non capisco. Se si esegue la mia versione tramite lo stesso validatore, viene restituito come JSON valido. – delliottg

+1

@delliottg Non utilizzare un validatore JSON per convalidare JavaScript. Per favore leggi di nuovo l'inizio della mia risposta. –

+2

@delliottg Non sto dicendo che è un JSON valido. Il punto di questa risposta è di differenziare JSON un oggetto JS. Prova a eseguire il codice dystroy in un interprete JS e vedrai che funziona alla perfezione. –

177

Basta mettere i dati in un oggetto come questo:

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

Successivamente stringa i via:

var myString = JSON.stringify(myObject); 

Non è necessario jQuery per questo. È puro JS.

+2

È possibile creare il nome dell'indice in modo dinamico. per esempio: var name = $ ('# myname').val(); myObject.name = "john" // qui l'indice del nome sarà dinamaclly da una casella di input. –

+3

Un bump per il commento precedente: per sostituire uno qualsiasi dei valori statici come '.name'' .age' o '.pets' basta sostituirlo, incluso il punto, con una variabile racchiusa tra parentesi quadre. Esempio: 'myObject [cssProp] = cssVal;' Quindi qualunque sia il valore di queste due variabili css sarà usato nell'oggetto. Ecco un jsFiddle: [http://fiddle.jshell.net/arttronics/rucjtbza/](http://fiddle.jshell.net/arttronics/rucjtbza/) – arttronics

4

Credo che stia chiedendo di scrivere il nuovo json in una directory. Avrai bisogno di alcuni Javascript e PHP. Quindi, per piggy back fuori le altre risposte:

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

Questo è bello ma la domanda non riguarda C# o ASP – Machavity

+0

@Machavity, dove trovi C# in questo? –

+1

Questo commento riguardava la prima revisione della tua risposta, che conteneva C# in essa. Ora ha ancora meno senso, dato che stai codificando la variabile 'model'. Questa domanda è: _ "In JavaScript, come posso creare un oggetto in runtime e rappresentare quell'oggetto nella notazione JSON" _, che la tua risposta non mostra ancora. – CodeCaster

0

annidata JSON oggetto

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

È possibile analizzare questo data.view.type e data.view.note

JSON oggetto e array all'interno

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

È possibile analizzare questo data.view[0].type e data.view[0].note

Problemi correlati