Home > Blockchain >  How to read json file with node.js using P5.js
How to read json file with node.js using P5.js

Time:02-08

I just want the word "flower" to show up

I have test terminal for Node and using the preload() and loadJSON(), it work just fine but the word flower not show up, meaning the "js file" does not run on "json file", but the terminal said on console it work for node(meaning it read the json file on terminal)

How do I debug this?

The below is what I use for learning and working on this project >

The Coding Train

10.2: What is JSON? Part I - p5.js Tutorial https://www.youtube.com/watch?v=_NFkzw6oFtQ

8.5: Saving Data to JSON File with Node.js - Programming with Text https://www.youtube.com/watch?v=6iZiqQZBQJY

index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>Sketch</title>

    <link rel="stylesheet" type="text/css" href="style.css">

    <script src="libraries/p5.min.js"></script>
    <script src="libraries/p5.sound.min.js"></script>
  </head>

  <body>
    <script src="infoJSON5.js"></script>
  </body>
</html>

infoJSON5.js

//var flower;

//function preload() {
//    flower = loadJSON("Data3.json")
    var fs = require('fs');
    var data = fs.readFileSync('Data3.json');
    var flower = JSON.parse(data);
    console.log(flower);
//}
    //Test Terminal
  /*
  node infoJSON5.js
  */

function setup() {
    createCanvas(400, 400);
}
  
  function draw() {
    background(0);

    fill(flower.r, flower.g, flower.b);
    text(flower.name, 10, 50);
  }

  

Data3.json

    {
"name":"sunflower",
"r":255,
"g":200,
"b":0
}

CodePudding user response:

JavaScript itself doesn't do input/output. If you want to read a JSON file you need to use an API provided by the host environment. Different host environments provide different APIs.

If the host environment is Node.js then, as you've found, you can use the fs module.

Web browsers are different. There would be major security problems if any webpage you visited could read files (specified by the JS code) from the user's disk.

In a web browser, you can use Ajax to fetch data from a URL. So you can host your JSON on a web server (usually alongside the webpage) and read it from there. MSN has a tutorial on Using Fetch for Ajax.

You can also use a file <input> and have the user select a JSON from file their hard disk (giving permission to read it) and then use the FileReader API.

CodePudding user response:

const myJSON =  {
"name":"sunflower",
"r":255,
"g":200,
"b":0
}
const myObj = JSON.parse(myJSON);



function setup() {
  createCanvas(400, 400);
}

function draw() {
   background(0);

    fill(myJSON.r, myJSON.g, myJSON.b);
    text(myJSON.name, 10, 50);
}
  •  Tags:  
  • Related