Parsing Json data from a file - javascript

I am building a Node JS application that reads file that contains array of Json objects, and displays it on a table. I need to parse the JSON data array.
sample json data:
[{"name":"Ken", "Age":"25"},{"name":"Pulsar", "Age":30}]
I have used the following to read from file and pass it into another json object:
const fileRead = fs.readFileSync("/Users/mken/Desktop/Node JS/DATA-TABLE/public/files/data.json", (err, data)=>{
console.log(JSON.parse(data))
return JSON.parse(data);
});
console.log(fileRead)
The expected output is array of JSON objects. However, when I console.log the fileRead, I do not get intended output:output
I further intend to iterate through the data read above and pass it to a JSON object:
const data = {headers:["Name", "Age"], rows: fileRead.foreach((row)=>{return row.name, row.age];})}
Please check and advise.

const fs = require('fs');
// Thanks to: https://nodejs.dev/learn/reading-files-with-nodejs
try {
const data = fs.readFileSync('test.txt', 'utf8');
console.log(data);
const json = JSON.parse(data);
console.log(json);
} catch (err) {
console.error(err);
}

the issue was with encoding. I passed utf-8 to filereadsync as second parameter, and it worked.
Thank you

If I do your task, I'll save data on a table, then I'll paste data to a json file and I'll read the file like your code.
I do that because I want to control the format of the JSON file. If you save a manual file in JSON, there are many ways you have problems with formatting JSON.
I hope my answer is helpful. Good luck!
 

Related

How to read and write to local JSON files from React.js?

I have looked at multiple resources for this, however, none seem to be able to answer my question. I have a local JSON file in my React app called items.json. In that file, is a list of objects, which I want to be able to update. I have tried using fs however this apparently doesn't work in React, as I received this error:
Unhandled Rejection (TypeError): fs.readFileSync is not a function
What I am trying to do, is that when the code gets a new item, it looks through the JSON file to see if there is an existing object with a matching values in its name property. If there is, it increments that objects count property by 1, otherwise it creates a new object, and appends it to the list in the JSON file. This is the code that I have written to do that. The logic seems sound (although its not tested) but I can't figure out how to read/write the data.
let raw = fs.readFileSync("../database/items.json");
let itemList = JSON.parse(raw);
let found = false;
for (let item of itemList.averages) {
if (item.name === this.state.data.item_name) {
found = true;
item.count += 1;
}
}
if (!found) {
let newItem = {
name: this.state.data.item_name,
count: 1,
}
itemList.averages.push(newItem);
}
let newRaw = JSON.stringify(itemList);
fs.writeFileSync("../database/items.json", newRaw);
The JSON file:
{
"averages": [
{
"name": "Example",
"count": 1,
}
]
}
First of all, the browser itself doesn't have access to the filesystem, so you won't be able to achieve that using your react app. However, this can be achieved if you use Node.js(or any other FW) at the backend and create an API endpoint which can help you to write to the filesystem.
Secondly, if you wanted to only do things on the frontend side without creating an extra API just for saving the data in a JSON file which I think is not necessary in your case. You can use localstorage to save the data and ask the user to download a text file using this :
TextFile = () => {
const element = document.createElement("a");
const textFile = new Blob([[JSON.stringify('pass data from localStorage')], {type: 'text/plain'}); //pass data from localStorage API to blob
element.href = URL.createObjectURL(textFile);
element.download = "userFile.txt";
document.body.appendChild(element);
element.click();
}
Now, To use local storage API you can check here - https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage
reading and writing JSON file to local storage is quite simple with NodeJs, which means a tiny piece of backend API in express would help get this job done.
few piece of code that might help you. Assuming you JSON structure would be such as below;
{
"name":"arif",
"surname":"shariati"
}
Read JSON file;
// import * as fs from 'fs';
const fs = require('fs')
fs.readFile('./myFile.json', 'utf8', (err, jsonString) => {
if (err) {
return;
}
try {
const customer = JSON.parse(jsonString);
} catch(err) {
console.log('Error parsing JSON string:', err);
}
})
customer contains your JSON, and values can be accessed by customer.name;
Write to JSON File
Let's say you have an update on your JSON object such as below;
const updatedJSON = {
"name":"arif updated",
"surname":"shariati updated"
}
Now you can write to your file. If file does not exist, it will create one. If already exists, it will overwrite.
fs.writeFile('./myFile.json', JSON.stringify(updatedJSON), (err) => {
if (err) console.log('Error writing file:', err);
})
Importing and reading from json can be like:
import data from ‘./data/data.json’;
then use .map() to iterate data.
for writing locally you can use some libraries like https://www.npmjs.com/package/write-json-file

Discord JS calling JSON

I'm currently working on a discord js bot which will fetch some information from a JSON file on a website. I have been able to get it to work with photos but I have no idea how to get the information I want from this JSON file. I'm sorry if this is really simple but I'm new to JS
The part I need from the JSON file is "name" and then I need it too print out all of the names that are in the file at the time.
This is currently a JSON file that I am testing with, it's a FiveM server player list.
http://145.239.206.148:30120/players.json
If you could please provide me with some information on how to get all of the player names that would be much appreciated.
This is the blank "Fivem" command file.
const Discord = require("discord.js");
module.exports.run = async (bot, message, args) => {
}
module.exports.help = {
name: "fivem"
}
You could parse the JSON file with JSON.parse() and traverse over each of the returned Object's array elements to access the name attributes and values. A JSON Parser would be helpful to visualize the indices of it's structure. Resources : JavaScript JSON Parsing
I used an api so I think you could do something like:
https.get('http://145.239.206.148:30120/players.json', response => {
response.setEncoding('utf8');
let body = '';
response.on('data', data => {
body += data;
});
response.on('end', () => {
body = JSON.parse(body);
console.log(body) // You obtain your json as an js object...
});
});
It worked for me so...
MrNossiom

Turning JSON.parse() return type to an array of object

I have defined a file called note-data.json which contains json data. In the following code a variable of type of array called notes is declared. What I want to achieve is that the program read the json file save it in the noteString variable and then make a array of object with JSON.parse() from noteString and put it into notes array. So I can add new objects to the json file. But when the programme gets to the line note.push() it complains since, I think, the type of notes has turned to a string and push is not define for string. How can I get around this issue?
Please ignore the fact that if the json file is not provided the the program crashes.
My code:
const addNote = (title, body) => {
let notes= [];
const note = {
title,
body
};
const notesString = fs.readFileSync('node-data.json', 'utf8');
notes = JSON.parse(notesString);
notes.push(note);
fs.writeFileSync('node-data.json', JSON.stringify(note));
}
File note-data.json:
{"title":"Greeting","body":"Hello"}
I think you are fumbling with your variables here. From what I understood - you want to read JSON from a file and append that JSON to an array, right? Following code will help you do just that
const addNote = (title, body) => {
let notes= []; //Declare an array
const note = JSON.parse(fs.readFileSync('node-data.json', 'utf8')); //read and parse file contents
notes.push(note); //Append new JSON to your array
//This line below appears to have no purpose ??
fs.writeFileSync('node-data.json', JSON.stringify(note));
}

why does my JSON file contain [object Object]?

I am using sqlite3 and nodeJS, and querying a database. I want to copy the queries into a json file. I run into problems with the json file having strings and objects. Why does my JSON file contain:
[object Object]
Here is my code:
db.all(sql, [], (err, rows) => {
if(err) {
throw err;
}rows.forEach((row) => {
arr_string = JSON.parse(JSON.stringify(row));
fs.writeFile("tempo.json", arr_string, function(err){
});
console.log(arr_string);
});
});
I would like to eventually use ajax requests for these entries.
arr_string = JSON.parse(JSON.stringify(row));
//^---------^--- This is parsing the string back to a new object.
You are parsing the stringified item to a new Object, hence the node.js file writer is trying to write the object to the write stream, resulting in interpreting it as [object Object].
Just omit the JSON.parse, so that the stream will effectively be a string instance:
arr_string = JSON.stringify(row);
Additionally, you should aggregate the result and write it only one time, or append to the file:
db.all(sql, [], (err, rows) => {
if(err) {
throw err;
}
let _strings = [];
const newline_separator = ''; // <-- use whatever separator you need.
rows.forEach((row) => {
arr_string = JSON.stringify(row);
console.log(arr_string);
_strings.push(arr_string);
});
fs.writeFile("tempo.json", _strings.join(newline_separator), function(err){});
});
Since it's a json, I would suggest you to provide us a more precise input, so that we can guess what the expected result is.
I think while storing JSON data into SQLite, you're not stringifying it. If you directly store JSON data into SQLite it'll store like [object Object] format. My suggestion is to stringify the data while storing in SQLite. And while retrieving only parse it. Then your problem will solve.
arr_string is actually not a string, as you JSON.parse d it. Remove the JSON.parse call.
The JSON.stringify() method converts a JavaScript value to a JSON string
arr_string = JSON.stringify(row);
"the problem now with doing that is now the JSON file only writes the last row (and i queried 4) and also I cannot call arr_string.caphi because its not an object anymore"
Create an empty array(list) and push each result of query in array.And then
finally convert it into JSON.
sample code :
var rows=[{"holla":"bolla"},{"holla":"bolla1"}];
console.log(JSON.stringify(rows));
JSON.stringify() takes JSON object and returns String
JSON.parse() takes String and returns JSON object
try :
rows.forEach((row) => {
arr_string = JSON.stringify(row); // 'row' data is converted to String
fs.writeFile("tempo.json", arr_string, function(err){
});`

How read JSON nested from Angular JS $http service?

This is my main JSON file
{
"chartType" : ["column", "column", "pie"],
"chartTitle": ["Cantidad de equipos", "Cantidad de artículos consumibles","Cantidad de empleados a cargo"],
"yAxisTitle": ["Equipos", "Consumibles", "Empleados"],
"seriesName": ["conexion_equipos_basededatos_json.php", "conexion_consumibles_basededatos_json.php", "conexion_basededatos_json.php"],
"seriesData": ["conexion_equipos_basededatos_json.php", "conexion_consumibles_basededatos_json.php", "conexion_basededatos_json.php"]
}
That loads others PHP JSON_ENCODE files in "seriesName" and "seriesData".
These JSON results generate keys "id" and "nombre" (spanish word for name).
How read values for these keys through Angular Service $http.get of the main JSON?
**UPDATE (06/03/2016)**
I'm middle of road!
I read the JSON objects from "seriesName" array with angular.fromJson function as follow:
var deserialize = angular.FromJson(data);
var objects = deserialize.seriesName;
console.log(objects);
That's throws me an array of objects:
["conexion_equipos_basededatos_json.php", "conexion_consumibles_basededatos_json.php", "conexion_basededatos_json.php"]
Thus, how I could read the objects contained in these URL's through Angular?
First of all you need to decode the JSON in PHP using json_decode(), then you treat the result as an object.
Try something like;
$data = xyz; // pass in the JSON object
$res = json_decode($data); // decode JSON
$chartType = $res->chartType; // access property as an object
You can also try var_dump($res) to get a clearer understanding of the structure and how to access it;
You can do following.
$http.get('url_to_json').then(fucntion(response) {
var myJson = response.data;
var keys = Object.keys(myJson);
console.log('Your keys', keys);
}, fucntion(error) {
});
Altough have button, I could resolve this issue.
I have created a repository that integrates Angular.js, PHP, and Highcharts, with Materialize.css, adding series dynamically from external JSON.
link: https://github.com/Nullises/DynamicSeriesHighchartsAngular

Categories

Resources