【问题标题】:jQuery JSON parse unexpected characterjQuery JSON 解析意外字符
【发布时间】:2014-02-04 18:07:42
【问题描述】:

我基本上读取了一些传感器数据,并将这些数据写入 JSON 文件。我试图在网页上显示这些读数,但我以前没有使用 jQuery 的经验。 我的measurements.json 文件包含与注释输出变量完全相同的内容。但是,当我使用注释行时,它可以工作。但是当我运行这里的代码时它不起作用;

<script type="text/javascript">
jQuery(document).ready(function(){

    $("#json").load('measurements.json');

    //var output = jQuery.parseJSON('{"timestamp": 1391524099.334835, "pH": 1.4132352941176471, "Temperature": -14.934640522815688, "Chlorine": 999.0},');

    var output = jQuery.parseJSON("#json");

    $('#celc').append(String(output.Temperature));
    $('#cl').append(output.Chlorine);
    $('#ph').append(output.pH);

});
</script>

<div id="json"><strong>JSON</strong>: </div>
<div id="celc"><strong>Temperatuur</strong>: </div>
<div id="cl"><strong>Chloor</strong>: </div>
<div id="ph"><strong>Zuur</strong>: </div>

我可能做了一些明显错误的事情,但我似乎无法仅使用 Google 来解决。

谢谢!

【问题讨论】:

  • 什么是,在最后一个被注释的 json 中
  • 您可能正在尝试在实际加载数据之前解析 json。

标签: javascript jquery json parsing


【解决方案1】:

你应该使用$.getJSON()

$.getJSON( 'measurements.json' function(data){
    $('#celc').append(String(data.Temperature));
    $('#cl').append(data.Chlorine);
    $('#ph').append(data.pH);
}).error(function() { alert("error"); });

.load() 被异步调用。因此,当您调用 jQuery.parseJSON("#json"); 时,它包含 &lt;strong&gt;JSON&lt;/strong&gt;: 这是无效的 JSON,因此您会遇到异常

【讨论】:

  • 感谢您的有用评论。我不再有任何错误!我不明白的是我的
    现在没有附加。或者也许它确实如此,但它只是空文本。有没有办法检查或解决这个问题?
猜你喜欢
  • 2013-05-31
  • 1970-01-01
  • 2022-01-01
  • 2017-04-10
  • 1970-01-01
  • 1970-01-01
  • 2018-08-18
  • 1970-01-01
  • 2020-07-22
相关资源
最近更新 更多