0

i have a NodeJs applet that I want to save the Users Array (Contains Objects) to a File, I am doing this with:

const fs = require('fs');
const util = require('util');
fs.writeFileSync('data/inventur_users.json', util.inspect(users), 'utf-8');

The Output in the File inventur_Users.json is:

[ BU4AFLx3cUYqdjvYPci7: { id: '5LkOWtVFcqz29UpsAAAC',
    name: '[email protected]',
    rechte: 'vollzugriff',
    client_ID: 'BU4AFLx3cUYqdjvYPci7' } ]

Now I am Reading the file back in with this code:

filedata = fs.readFileSync('data/inventur_users.json', 'utf-8');

My Problem is that i only get a String and I don't know how to convert the String back to an Array that contains Objects.

Thanks in advance, Patrick

2 Answers 2

1

Firstly

[ BU4AFLx3cUYqdjvYPci7: { id: '5LkOWtVFcqz29UpsAAAC',
    name: '[email protected]',
    rechte: 'vollzugriff',
    client_ID: 'BU4AFLx3cUYqdjvYPci7' } ]

is not a valid json, you can verify it from here https://jsonlint.com/

Valid json would look like

[{
    "BU4AFLx3cUYqdjvYPci7": {
        "id": "5LkOWtVFcqz29UpsAAAC",
        "name": "[email protected]",
        "rechte": "vollzugriff",
        "client_ID": "BU4AFLx3cUYqdjvYPci7"
    }
}]

and then you can directly require content of .json file in a variable like

const filedata = require('data/inventur_users.json');
Sign up to request clarification or add additional context in comments.

15 Comments

Thank you for your reply, how can i convert an array to a json? And if i Import the json, can i use it like i used the array? Patrick
[1, 2, 3] is a valid json so you can store it directly in json file and while requiring it, yes you can use it directly like an array. You can use jsonlint.com to verify what is valid json and what is not
So i was able to export the Array to a valid Json, but if i want to import it with require i get this error: 'Error: Cannot find module 'data/inventur_users.json' but the json is in that directory
try with require('./data/inventur_users.json');
Now i can read the json but it gives me a string of the json without the " at the beginning and the end
|
0

You can use JSON.parse() to convert the string back to a JavaScript object:

filedata = JSON.parse(fs.readFileSync('data/inventur_users.json', 'utf-8'));

You should also use JSON.stringify() to save the file in the first place:

fs.writeFileSync('data/inventur_users.json', JSON.stringify(util.inspect(users)), 'utf-8');

3 Comments

I did it like in your example but filedata is still a string.
Have you also used JSON.stringify(...) to save the file?
Here you can see the code, json and output: pastebin.com/nZqZNdpy

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.