How to transform data into array with JSON?

Asked

Viewed 4,171 times

0

I have to get the data that are being accumulated in the variable valore and turn them into an array so you can catch them using HttpRequest in an HTML page. How do I do this?

// Classe para chamar o JSON.
function json(){
	var qtd;
	var retorno;

	// Resgatar valores.
	json.prototype.resgatarValores = function(){
		$('#resultado').html('Carregando dados...');

		// Estrutura de resultado.
		$.getJSON('/webpro/webadm/lncidjson', function(data){
			this.qtd = data.usuarios.length - 1;
			this.valore = '';
			this.label = '';

			for (i = 0; i < this.qtd; i++){
				if(i == (this.qtd - 1)) {
					this.valore += data.usuarios[i].valor;
					this.label += data.usuarios[i].descr;
				} 
				else {
					this.valore += data.usuarios[i].valor + ',';
					this.label += data.usuarios[i].descr + ',';
				}
			}

			$('#valor').html(this.valore);
			$('#label').html(this.label);
		});

	}

}

// Objeto.
var obj = new json();
obj.resgatarValores();

  • To turn an object into json you don’t need to create a class, javascript already does it natively.

  • http://answall.com/q/42809/14674 , http://answall.com/q/5656/14674

  • Values are not yet an array they are only assigned to the variable.

  • You can use native methods to transform (parse) the information into a JSON. var seuJson = JSON.parse(valore);

  • Depending on how your object looks of course, if you don’t need to format it to parse.

3 answers

3


//obj.resgatarValores();
var obj= [{nome:"Marcelo",idade:20},{nome:"Teste",idade:90}];

var b =JSON.stringify(obj);
document.writeln(b)

0

0

You can do this conversion in the web layer, as presented by user3120449, as do in the backend depending on the language used, in . NET we have the class Javascriptserializer that performs the work.

    var keyValues = new Dictionary<string, string>
           {
               { "emailSend", textBox1.Text },
               { "toEmail", textBox2.Text }
           };

    JavaScriptSerializer js = new JavaScriptSerializer();
    string json = js.Serialize(keyValues);
    MessageBox.Show(json);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.