Home > database >  How to read JSON file in Java script file
How to read JSON file in Java script file

Time:03-31

I'm trying to read the JSON file in my javascript file.

const jsonData = require('folder/file.json');
console.log(jsonData);

It got a error "require is not defined".

I need to know how to load the JSON from my file.

CodePudding user response:

Maybe you could use Node fs.readFile() method:

const fs = require('fs')

    fs.readFile('folder/file.json', 'utf8' , (err, data) => {
      if (err) {
        console.error(err)
        return
      }
      console.log(data)
    })

Here is the link to the documentation

CodePudding user response:

create a local json and save (sure you have one)

jsonData = '[{"name" : "Username", "age" : "20"},{"name" : "Username2", "age" : "20"}]';

import the script

<script type="text/javascript" src="./path/.../localJsonFileName.json"></script>

Save in variable and do stuff

var myLocalJson = JSON.parse(jsonData);
Console.log(myLocalJson);
  • Related