0

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>
5
  • 5
    The string value "[1, 5, 'false']" is not JSON. The string '[1, 5, "false"]' is. See json.org Commented Oct 7, 2013 at 20:37
  • 3
    ... and perhaps the intention was actually "[1, 5, false]"? Commented Oct 7, 2013 at 20:37
  • Damn, so dumb sometimes!, thanks Commented Oct 7, 2013 at 20:38
  • Well, I also missed pointing that a string like "foo" doesn't have a data member. Commented Oct 7, 2013 at 20:39
  • A string may not, but the expected dispatched event argument does have a data member (as well as origin and source). Commented Oct 7, 2013 at 20:48

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

0

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.