2

I'm working on a small server (NodeJS environment) to get JSON data from a URL and a local file to compare these.

I'm using 'get-json' to load the JSON form the url and get some values, unfortunately it doesn't work for the local file.

I tried it with 'request' too.

var getJSON = require('get-json')
var localpath = "./location/file.json"

getJSON(localpath, function(data, allowed_content) {
  var a = allowed_content[0].age;
  var b = allowed_content[1].age;
  var c = allowed_content[2].age;
  var d = allowed_content[5].age;
  var e = allowed_content[6].age;
});

I can't figure it out why the local path isn't working.

Reinstate Monica Cellio
  • 25,975
  • 6
  • 51
  • 67
Markde23
  • 21
  • 2

3 Answers3

1

You can simply use fetch function

var localpath = "./location/file.json"
    fetch(localpath)
    .then(response => response.json())
    .then(json => {
      console.log(json);
    }); 
Saurabh Yadav
  • 3,303
  • 1
  • 10
  • 20
0

tl;dr don't use get-json to read local files but use readFile

get-json is for network request, its docs says it wraps around requests in node, and uses JSONP on the browser. To read a local file just use readFile or readFileSync:

var { readFileSync } = require("fs");
var localPath = "";
var localFile = readFileSync(localPath, "utf8"); // utf8 is opts and depends on your setup, the async version of readFile takes a callback as last argument
console.log(JSON.parse(localFile));
adz5A
  • 2,012
  • 9
  • 10
  • It's working, now I need to figure out how I can get the specific values from the value. like "allowed_content[6].age" – Markde23 Jul 29 '19 at 12:34
  • Not sure I follow you. Calling `JSON.parse` on a string should return a JS object (or throw an error). Name the output `allowed_content` and you can access all its properties using regular syntax – adz5A Jul 29 '19 at 12:40
  • I mean, I need specific values from the JSON file. I'll try to figure it out. Thanks again for your help! – Markde23 Jul 29 '19 at 12:45
  • Ah, good luck with this. If you have a memory limit issue you might be interested in http://oboejs.com/ wich is a json streaming library. If my answer is OK can you accept it ? – adz5A Jul 29 '19 at 12:48
0

The solution was real easy actually:

var myvar = require('./filepath/myfile.json');
var a = myvar[0].age;
var b = myvar[1].age;
var c = myvar[2].age;
var d = myvar[5].age;
var e = myvar[6].age;
Markde23
  • 21
  • 2