OBV
OBV

Reputation: 1259

JSON.parse doesn't seem to parse object data?

I am communicating between iframes, but json.parsing to a var then using document.write to dump it doesn't contain anything. But if I alert(e.data), it does.

<script>
window.onmessage = function(e) {

var j = JSON.parse(e.data);
document.write(j);
}
</script>

<script>window.postMessage("[1, 5, 'false']", '*');</script>

Upvotes: 0

Views: 131

Answers (2)

Esteban
Esteban

Reputation: 3127

JSON.parse() is defined in ECMA-262, fifth edition, almost any browser supports it.

How to use it?

var json = '{"prop":"first","prop2":1}';
var o = JSON.parse(json);

If you're using jquery, it has a parse json function $.parseJSON, but its slower than native JSON.parse, so it's better to use the jquery function if the JSON object is not available.

var json = '{"prop":"first","prop2":1}';
var o = JSON && JSON.parse(json) || $.parseJSON(json);

Upvotes: 0

Andr&#233;s Torres
Andr&#233;s Torres

Reputation: 733

For a correctly parse of a string into a JSON object strings keys and values must be wrapped by quotes "

Upvotes: 1

Related Questions