drno94939847 2015-01-28 17:33 采纳率: 0%
浏览 29
已采纳

在javascript中使json正确

I am trying to setup an analytics script in which I use json like this:

var visitors = [
    { date: "2014-01-11", value: 7 },
    { date: "2014-01-12", value: 2 },
    { date: "2014-01-13", value: 5 },
];

Now, I am getting my json through ajax from an php page like this:

jQuery.getJSON( "assets/ajax/flurry.php", { method: "ActiveUsers" } )
  .done(function( json ){

    var visitors = json; 
    console.log( "JSON Data: " + json );

});

This produces this:

JSON Data: [object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]

My output from the php page look like this:

[{"@date":"2015-01-14","@value":"948"},{"@date":"2015-01-15","@value":"4720"},{"@date":"2015-01-16","@value":"4989"},{"@date":"2015-01-17","@value":"5221"},{"@date":"2015-01-18","@value":"5658"},{"@date":"2015-01-19","@value":"5484"},{"@date":"2015-01-20","@value":"5508"},{"@date":"2015-01-21","@value":"5560"},{"@date":"2015-01-22","@value":"5576"},{"@date":"2015-01-23","@value":"5452"},{"@date":"2015-01-24","@value":"5524"},{"@date":"2015-01-25","@value":"5804"},{"@date":"2015-01-26","@value":"5714"},{"@date":"2015-01-27","@value":"5478"},{"@date":"2015-01-28","@value":"0"}]

How do I get it to produce an javascript json like the first one?

Any help is appreciated :-)

  • 写回答

4条回答 默认 最新

  • dongmeiyi2266 2015-01-28 17:38
    关注

    When you use the following line:

    console.log( "JSON Data: " + json );
    

    The code casts the entire object as a string, which is usually not a very useful things as it replaces anything that is an object with this nice [object Object] you're getting.

    You could either log the object itself in a separate parameter:

    console.log( "JSON Data: ", json );
    

    Or dump the JSON representation of the object:

    console.log( "JSON Data: ", JSON.stringify(json));
    

    But you'll probably see that your json variable is already what you expected.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?