Json数据键值,Object.Keys错误

时间:2017-08-28 20:55:55

标签: javascript jquery json

我试图从json数据中解析出所有键。

<script type="text/javascript">
    $(document).ready(function () {
        $.ajax({
            type: "POST",
            url: "History.aspx/GetFTEData",
            dataType: "json",
            contentType: "application/json; charset=utf-8",
            success: function (data) {
                var returnedstring = data.d;
                var colHeader = Object.keys(data[0]); <---- error line

            }
        });
    });
</script>

但是,var colHeader = Object.keys(data[0]);这在我的IE 11或Firefox浏览器上使用我的IDE(VS2015)运行它时不起作用,即使它在jsfiddle示例中有效: -

https://jsfiddle.net/qpu3cn5u/

错误消息: - 0x800a138f - JavaScript运行时错误:Object.keys:参数不是对象

我有哪些替代品?这样我只能将键解析为我试图用值填充的html表的列名。

数据示例: -

var data = `[{"Customer Name":"XXXX","1999":76.000,"2000":68.000,"2001":49.000,"2002":41.000,"2003":47.000,"2004":56.000,"2005":33.000,"2006":51.000,"2007":56.000,"2008":52.000,"2009":55.000,"2010":52.000,"2011":57.000,"2012":55.000,"2013":93.000,"2014":92.000,"2015":62.000,"2016":71.833},{"Customer Name":"YYYYY","1999":29.000,"2000":27.000,"2001":35.000,"2002":37.000,"2003":32.000,"2004":29.000,"2005":44.000,"2006":49.000,"2007":69.000,"2008":109.000,"2009":108.000,"2010":150.000,"2011":189.000,"2012":215.000,"2013":53.000,"2014":78.000,"2015":65.000,"2016":63.000},{"Customer Name":"ZZZZ","1999":0.000,"2000":0.000,"2001":0.000,"2002":0.000,"2003":0.000,"2004":0.000,"2005":0.000,"2006":0.000,"2007":0.000,"2008":0.000,"2009":0.000,"2010":0.000,"2011":0.000,"2012":28.000,"2013":36.000,"2014":59.000,"2015":90.000,"2016":94.000},{"Customer Name":"AAAAA","1999":0.000,"2000":0.000,"2001":0.000,"2002":0.000,"2003":0.000,"2004":0.000,"2005":0.000,"2006":0.000,"2007":0.000,"2008":0.000,"2009":0.000,"2010":0.000,"2011":0.000,"2012":18.000,"2013":18.000,"2014":18.000,"2015":19.000,"2016":18.000}]`

2 个答案:

答案 0 :(得分:1)

似乎问题是data[0]仍处于JSON状态。当您编码单个对象,然后编码它们的封闭数组时,通常会发生这种情况。单个对象得到双重编码。

作为测试,试试这个:

var parsed = JSON.parse(data[0]);
console.log(Object.keys(parsed));

如果这显示了您想要的结果,那么它会告诉您双重编码是问题。

然而,再次解析它不是解决方案。您需要在生成JSON数据的服务器上修复此问题,以便不会对其进行双重编码。

答案 1 :(得分:0)

如果您必须支持旧浏览器,您可以随时尝试使用旧样式/ API查找如何执行类似任务的示例。例如,您可以通过执行以下操作来遍历JavaScrip对象道具:

$this->app->make('Package\Avatar\AvatarController');

找到类似的问题/代码示例here

但是,for (var property in object) { if (object.hasOwnProperty(property)) { // do stuff } } 支持是所有主流浏览器。包括IE11,参考here