Extracting info from a JSON: P5.js

4.3k views Asked by At

my php script json_encodes this:

[{"x":"20","y":"24","name":"NewNov"},{"x":"20","y":"70","name":"Tito"}]

But I can't see how I can extract this information in my p5.js program?

Say, I need to use those 'x', 'y', 'name' to draw a circle in the appropriate place with the right name.

I used loadJSON in the script, and now I have a variable -

data = loadJSON()

But how do I get, say, the 'x' component from the JSON?

var radius;

function preload() {
    var url = 'http://localhost/planetTrequest.php';
    radius = loadJSON(url);
}

function setup() {
    createCanvas(300, 300);
    background(153);
    noLoop();
}

function draw() {
    background(200);
    textSize(15);
    text(radius.x, 10, 30);
    fill(0, 102, 153);
}
4

There are 4 answers

2
Stefan Dimov On

Your data is in an array with two objects (the jsons).

var firstObj = data[0]; // get the first element from array
var secondObj = data[1]; // get the second element

firstObj.x return you x from the first json.

0
TaoPR On

Just for a quick example

Given you have an input returned as JSON like:

var data = [{"x":"20","y":"24","name":"NewNov"},{"x":"20","y":"70","name":"Tito"}];

If you want to extract x, y, name from each of the elements in that array, you can do:

for (var element of data){
    // Your element is in format : 
    // {"x":"20","y":"24","name":"NewNov"}

    // To get X
    var x = element.x; // or element["x"]
    // To get Y
    var y = element.y; // or element["y"]
    // To get name
    var name = element.name; // or element["name"]

    // Do whatsoever with your element
    // ...
}

** JSON is an object**

You can quickly access any property in your JSON data via its key as demonstrated above in the code. You basically have two ways, access with . property or [] array index notation.

0
Алексей Наумов On

Thanks to all the comments above, that's what worked in the end:

 var data;

 function preload() {
 var url = 'http://localhost/planetTrequest.php';
 data = loadJSON(url);
 }

 function setup() {
 createCanvas(300, 300);
 background(153);
 noLoop();
 }

 function draw() {
 background(200);
 textSize(15);
 text(data[0].name, 10, 30);
 fill(0, 102, 153);
 }  
0
ggorlen On

loadJSON is asynchronous, which means the data won't be immediately available. loadJSON works by populating the properties on the object it returns when called inside preload because p5 won't call setup or draw until all asynchronous calls in preload have resolved.

According to the docs:

Calling loadJSON() inside preload() guarantees to complete the operation before setup() and draw() are called.

The normal setup is as follows:

let data; // expose the result object's variable globally

function preload() {
  /* endpoint to get an example JSON with a `title` property: 
      {"title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit"} 
  */
  const url = "https://jsonplaceholder.typicode.com/posts/1";

  data = loadJSON(url);    // get a reference to a placeholder object that 
                           // will be filled in before draw/setup

  console.log(data.title); // guaranteed to be undefined!
                           // p5 hasn't waited for the call to complete yet
}

function setup() {
  createCanvas(500, 150);
  noLoop();
  console.log(data.title); // data.title is defined!
}

function draw() {
  background(200);
  textSize(15);
  textAlign(CENTER, CENTER);
  text(data.title, width / 2, height / 2); // data.title is defined!
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.6.0/p5.js"></script>

When using loadJSON outside of preload, p5 doesn't do anything special to wait for the load to finish. The docs recommend supplying a callback to loadJSON that is called with the response data when it arrives:

function setup() {
  const url = "https://jsonplaceholder.typicode.com/posts/1";
  //let title; // wrong! this can't expose data for this block to access
  
  loadJSON(url, data => {
    //title = data.title; // wrong! this won't set the outer 
                          // variable let title; in time for 
                          // the bottom console.log(title)
    
    // correct! now you can consume the data
    console.log(data.title);
  });
  
  //console.log(title); // wrong! title will be undefined here
  noLoop();
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.6.0/p5.js"></script>

Keep in mind loadJSON is not the only way to get JSON data. You can use any other library to get the data. loadJSON won't be defined outside of p5 functions. On Node, axios is a good bet. In the browser, fetch is a good bet.

See also Return response from asynchronous call for an in-depth guide to the callback pattern shown above. You can promisify the callback and otherwise use techniques in this thread for accessing the data from the response in a way that works for your needs (this goes beyond the scope of p5 and the normal use cases for loadJSON).