使用 json 作为输入进行处理

Processing using json as input

我有一个处理文件,它试图绘制一个半径取决于变量的椭圆。

现在我不想简单地在处理文件中定义变量,而是从 json 文件中导入值。

我试过以下方法:

JSONObject json;

void setup() {
  size(500,500);

  json = loadJSONObject("data.json");

  int max = json.getInt("max");
  int avg = json.getInt("avg");
  int min = json.getInt("min");

  print(max);
}

void draw() {
 ellipse(10,10,max,min);
}

不幸的是,我收到错误消息:max 无法解析为变量。

这里还有 json 文件的外观。 data.json:

[{
    "Max Temperature": {
      "max": "18", 
      "avg": "6", 
      "min": "-2"
    }
  }
 ]

您可以使用loadJSONObject()功能。

参考文献中的示例:

// The following short JSON file called "data.json" is parsed 
// in the code below. It must be in the project's "data" folder.
//
// {
//   "id": 0,
//   "species": "Panthera leo",
//   "name": "Lion"
// }

JSONObject json;

void setup() {

  json = loadJSONObject("data.json");

  int id = json.getInt("id");
  String species = json.getString("species");
  String name = json.getString("name");

  println(id + ", " + species + ", " + name);
}

// Sketch prints:
// 0, Panthera leo, Lion

编辑: 请注意本示例 JSON 和您的 JSON 的区别。您的 JSON 包含 一个名为 Max Temperature 的字段。该字段本身是一个 JSONObject,它包含 3 个字段:maxavgmin.

要到达 max 字段,您必须先通过 "outer" JSON 对象。它可能看起来像这样:

JSONObject json = loadJSONObject("data.json");
JSONObject maxTemperature = json.getJSONObject("Max Temperature");
int max = maxTemperature.getInt("max");

可以在 the reference 中找到更多信息。