Domanda

I am trying to json encode a variable to have the value of undefined, as in the javascript keyword undefined. I tried to google this, but the only results that show up are about people getting errors in their php script that the actual function json_encode is undefined. Is there a way to do undefined? To encode the value NULL it is simply null without quotes. Using "undefined" in php treats it as a string, and of course undefined doesn't work since php thinks that is a constant.

I tried this in javascript:

JSON.stringify([undefined,null]);

but it returned

[null,null]

So is it even possible to encode the value undefined?

The reason I am asking is that I am using the morris.js charting library, and it handles null values differently than undefined values when your line chart is missing data points, and I want them to be handled as undefined. I realize I could loop thru my JSON object and convert all nulls to undefineds, but I want to know if it is even possible to encode undefined.

In general, there are several situations where undefined may be handled differently than null so this would be applicable to all of them.

Thanks!

È stato utile?

Soluzione

No. JSON does not support a value of undefined. The closest relatives would be null or false. According to the specification, valid JSON values are: string, number, object, array, true, false, and null.

Moreover, how would you check for its existence in an object?1

var a = {"key1":undefined,"key2":"value2"};
var b = {"key2":"value2"};
if(typeof(a.key1) == typeof(b.key1)){
    alert('absent in both!');
}

See my fiddle.

If you want a property to be undefined, remove it, for example in PHP use unset before json_encode:

$a = array('key1' => null, 'key2' => 'value2');
unset($a['key1']);
json_encode($a); // {"key2":"value2"}

1 You can use a for...in loop.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top