how to access json data in processing.js

自古美人都是妖i 提交于 2019-12-25 03:22:30

问题


I am trying to access json data which is there inside data folder inside my project folder. But I am getting "Uncaught Processing.js: Unable to execute pjs sketch: ReferenceError: loadJSONArray is not defined" error.

The JSON Data is as follows:

[
    {
       "month": "january", 
       "total": 32393, 
       "disease": 2761, 
       "wounds": 83, 
       "other": 324
    },
    {
       "month": "february", 
       "total": 30919, 
       "disease": 2120, 
       "wounds":  42, 
       "other": 361
    }
]

This is my HTML file and I am using processing version 1.3.6.

<html>
<head>
    <script src="processing-1.3.6.js"></script>
</head>
<body>
    <canvas data-processing-sources="demo.pde"></canvas>    
</body>
</html>

Following is my processing code. (demo.pde)

JSONArray values;

void setup() {
size(800,600);
background(255);
noLoop();

values = loadJSONArray("data/data.json");

for (int i = 0; i < values.size(); i++) {
    JSONObject deads = values.getJSONObject(i); 
    int total = deads.getInt("total");
    String month = deads.getString("month");
    println(total + ", " + month);
}
}

回答1:


If you are able to install jQuery, you can easily call methods such as $.ajax({}) or more specifically $.getJson({}) whereby you can loop through your results with $.each.

Example given in the jQuery API documentation:

$.getJSON( "data/data.json", function( data ) {

  $.each( data, function( key, val ) {
   // YOUR CODE
   // example: 
   var result = val.total + ' ' + val.month;
  });

});

UPDATE:

Here is a quick JsFiddle showing how to use the $.each()




回答2:


Processing.js does not have support for loadJSONArray yet, plus all data requests are asynchronous in JavaScript, so loadJSONArray can't work the way the Processing API makes it work right now.

You can simply load the values in plain JS context, and then feed them into your sketch (following http://processingjs.org/articles/PomaxGuide.html or the like)



来源:https://stackoverflow.com/questions/28630004/how-to-access-json-data-in-processing-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!