Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why am I getting [object Object] instead of JSON?

This is the script:

$("#some_button").click(function() {

    var changed = [];

    $( 'input[id$="_1"]' ).each(function() {

        var new_id = this.id.replace( '_1', '_0' );

        if ( $(this).val() !== $( 'input#' + new_id ).val() ) {

            changed.push({id:new_id, new_val:$('input#' + new_id).val(), old_val:$(this).val()});

        }

    });

    alert(changed);

});

and it's gives me [object Object],[object Object].

What am I doing wrong?

like image 600
nami Avatar asked Jul 14 '11 09:07

nami


People also ask

Why do I get object object JavaScript?

[object Object] is a string version of an object instance. This value is returned by a JavaScript program if you try to print out an object without first formatting the object as a string. It's no wonder developers get confused about this object: there are no error messages or warnings that tell us what is going on.

Is JSON same as object?

JSON cannot be an object. JSON is a string format. The data is only JSON when it is in a string format.

How do you Stringify an object object?

Stringify a JavaScript ObjectUse the JavaScript function JSON.stringify() to convert it into a string. const myJSON = JSON.stringify(obj); The result will be a string following the JSON notation.


2 Answers

Because you don't have JSON. You have an array: []. JSON is a string representation of a javascript object.

You could use the JSON.stringify method to generate a JSON string from an existing object:

alert(JSON.stringify(changed));

The JSON.stringify method is native in modern browsers but if you need to support legacy browsers you will need to include json2.js to your page. This script checks whether the browser supports natively JSON.stringify and uses it, or if it doesn't it provides a sample implementation.

like image 68
Darin Dimitrov Avatar answered Oct 23 '22 06:10

Darin Dimitrov


JSON is one way to display/encode JavaScript objects, but it's not used by default. When you convert an object to a string you'll normally just get a useless value like "[object Object]".

If you want to convert your object into a JSON string, you need to use the JSON.stringify function. (This is included in new browsers, but requires a JSON library in older ones.)

In your case, you probably want to replace your alert line with

alert(JSON.stringify(changed));
like image 28
Jeremy Avatar answered Oct 23 '22 07:10

Jeremy