Gavin Sutherland
Gavin Sutherland

Reputation: 1686

JSON.stringify not working in IE10

I am trying to parse some form data to produce JSON data to send in an ajax request. The following HTML is an oversimplified version of my code. I'm using APS.Net MVC4 and my rendered view produces the following HTML:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
    <link href="/Content/site.css" rel="stylesheet"/>
    <script src="/Scripts/modernizr-2.6.2.js"></script>
</head>
<body>

<div class="test-class" data-my-attribute="1"></div>
<div class="test-class" data-my-attribute="2"></div>
<div class="test-class" data-my-attribute="3"></div>

<script src="/Scripts/jquery-1.8.2.js"></script>

<script type="text/javascript">
    $(function () {
        jsonObj = [];
        $(".test-class").each(function () {
            var myAttribute = $(this).data('my-attribute');
            item = {}
            item["MyAttribute"] = myAttribute;
            jsonObj.push(item);
        });
        var data = { SomeOtherData: 1234, MyAttribs: jsonObj };
        console.log(JSON.stringify(data));
    });
</script>
</body>
</html>

In Chrome the output in the console is output as expected ...

{
    "SomeOtherData": 1234,
    "MyAttribs": [{
        "MyAttribute": 1
    }, {
        "MyAttribute": 2
    }, {
        "MyAttribute": 3
    }]
}

... but in IE the objects come out as null ...

{
    "SomeOtherData": 1234,
    "MyAttribs": [null, null, null]
}

I've had a look around and found some other questions that recommend checking that the page has <!DOCTYPE html> in it (which it does) and that doesn't seem to have any effect. I've also read that this should work in from IE8 onward so not sure what's happening.

  1. Does anyone know why the objects are appearing as nulls in IE?
  2. What is the best cross-browser solution to this?

Thanks, Gavin

Upvotes: 1

Views: 4144

Answers (2)

on my case use as @palvo sayed console.dir(obj)

other alternative is JSON2 from douglascrockford

Upvotes: -1

QuarK
QuarK

Reputation: 2536

The only weird thing I see is that:

  item = {}

Should be:

  var item = {}; // 'var' and semicolon

Sometimes IE is quite strict..

Upvotes: 11

Related Questions