0

This is an example copied from Java Processing tutorials and would like to have something like that in Python Processing.

    
String[] species = { "Capra hircus", "Panthera pardus", "Equus zebra" };
String[] names = { "Goat", "Leopard", "Zebra" };

JSONArray values;

void setup() {

  values = new JSONArray();

  for (int i = 0; i < species.length; i++) {

    JSONObject animal = new JSONObject();

    animal.setInt("id", i);
    animal.setString("species", species[i]);
    animal.setString("name", names[i]);

    values.setJSONObject(i, animal);
  }

  saveJSONArray(values, "data/new.json");
}

This is what I've already tried in Python.

import json

values = JSONArray

species = [ "Capra hircus", "Panthera pardus", "Equus zebra"]
names = [ "Goat", "Leopard", "Zebra" ]

def setup():
    for i in range(len(species)):
        animal = JSONObject

        animal.setInt("id", i)
        animal.setString("species", species[i])
        animal.setString("name", names[i])

        values.setJSONObject(i, animal)

    saveJSONArray(values, "data/new.json")

After running the program I'm getting the following error:
NameError: name 'JSONArray' is not defined

I know there should be another way of declaring JSON object in Python Processing but I am new to Python so I have no idea what the mistake could be.

Thanks in advance :)

2 Answers 2

1

values ==JSONArray is completely wrong There is no declared like that in python.

I guess First you should check python tutorials. For your question

array = '{"fruits": ["apple", "banana", "orange"]}'
data  = json.loads(array)
print data['fruits']

is a good example for your problem.

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

1 Comment

link is a good solution.
0
import json

annotations = [0,1,2]
species = [ "Capra hircus", "Panthera pardus", "Equus zebra"]
names = [ "Goat", "Leopard", "Zebra" ]


def setup(anotations, species, names):
    values = []

    for idx, _ in enumerate(annotations):
        animal = {
            "id": idx,
            "species": species[idx],
            "name": names[idx]
        }

        values.append(animal)

    with open("data_file.json", "w") as write_file:
      json.dump(values, write_file)


if __name__ == "__main__":
  setup(annotations, species, names)

Comments

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.