1

I basically read some sensor data and this data gets written to a JSON file. I'm trying to show these readings on a web page but I have as good as no previous experience with jQuery. My measurements.json file contains exactly the same as the commented output var. However when i use the commented line it works. But it does not work when i run the code like here;

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

Im probably doing something obvious wrong but i cant seem to figure it out using just Google.

Thanks!

2
  • 3
    what is , in last of json that is comented Commented Feb 4, 2014 at 18:09
  • 2
    You're probably trying to parse the json before the data was actually loaded. Commented Feb 4, 2014 at 18:10

1 Answer 1

4

You should use $.getJSON().

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

.load() is called asynchronously. Thus when you call jQuery.parseJSON("#json"); it contains <strong>JSON</strong>: which is invalid JSON thus you are getting exception

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

1 Comment

Thanks for the useful comment. I'm not getting any errors any more! What I don't understand is that my <div id>'s now don't get append. Or maybe it does but its just empty text. Is there a way to check or solve this?

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.