jprichardson / node-jsonfile

Easily read/write JSON files.
MIT License
1.2k stars 321 forks source link

No commas #85

Closed ghost closed 7 years ago

ghost commented 7 years ago

Hi there, when i write to an existing json file, no commas are added.

thanks

[{
  "messageID": 1111,
  "senderID": "AAAA",
  "senderName": "TwitterUser",
  "message": "This is the message"
}
{
  "messageID": 2222,
  "senderID": "BBBB",
  "senderName": "TwitterUser2",
  "message": "This is the message2"
}]
RyanZim commented 7 years ago

What version of Node.js & jsonfile?

ghost commented 7 years ago

node.js v6.10.0 jsonfile@3.0.1

I managed to add them manually in the jsonfile index.js file.

fs.writeFile(file, ','+str, options, callback);

but i need to make an array within the json file. is this possible?

[{ "name": "a" },{ "name": "b" }{ "name": "c" }]

Regards

RyanZim commented 7 years ago

@tetpsy Please make a reduced test case repo that demonstrates this issue and post the link here. Thanks!

ghost commented 7 years ago

Thanks, but i don't know how to show a test case with a file edit..

If i can explain a bit better.

From what i see, jsonfile creates and edits json files with node.js

I dont see any documentation on how one would write to an existing file with commas separating each object. I cannot read the json file if its not structured in an array format with comma separated objects.

How i think the code works now is it just adds objects to my json file, but the file is not useable afterwards.

Thanks

RyanZim commented 7 years ago

Please post the exact code you're using to write to the json file.

ghost commented 7 years ago

I first added to the json file with this

// Json file functions
    var jsonfile = require('jsonfile')

    var file = 'data.json'
    var obj = {name: 'JP'}

    jsonfile.writeFile(file, obj, function (err) {
      console.error(err)
    })

it saved as

{"name":"JP"}

Then i appended with this

var jsonfile = require('jsonfile')
var file = 'data.json'
var obj = {name: '2nd'}

jsonfile.writeFile(file, obj, {flag: 'a'}, function (err) {
    console.error(err)
})

and it saved as

{"name":"JP"}
{"name":"2nd"}

i wanted it to save like this

{"name":"JP"},
{"name":"2nd"}

or even better like this

[{"name":"JP"},
{"name":"2nd"}]
RyanZim commented 7 years ago

jsonfile can't do this for you. You need to write an array, then you can do:

var jsonfile = require('jsonfile')
var file = 'data.json'
var obj = {name: '2nd'}

jsonfile.readFile(file, function (err, data) {
  console.error(err)
  jsonfile.writeFile(file, data.push(obj), function (err) {
    console.error(err)
  })
})

to append the file.

ghost commented 7 years ago

Thanks dude

Big ups

jacobedawson commented 7 years ago

@RyanZim or @tetpsy could you please show an example of 'writing an array'? I've tried several methods and still can't seem to be able to append data using the technique shown above.

Any assistance / examples would be much appreciated :)

Thanks,

Jake

ghost commented 7 years ago

Yes it seems that you cannot make an json array with the code as is, maybe you can try customize the script yourself (isn't too advanced in the node module) or find another plugin?

thanks

ghost commented 7 years ago

Oh actually, check @RyanZim example, that should work?

jacobedawson commented 7 years ago

@tetpsy All good I got it working. Personally I understand best when I can see the code described, it's harder for me to conceptualize otherwise. For anyone else running into this issue, this is the solution I came up with (this code might not fit your exact use case but you can see the method of creating an array and writing it to the file_:

function appendToFile(post) {
    const path = './server/processing';
    try {
        fs.accessSync(path);
    } catch (e) {
        fs.mkdirSync(path);
    }
    const file = './server/processing/test.json';
    jsonfile.readFile(file, (err, data) => {
        if (err) {
            const x = {
                "data": [
                    post
                ]
            };
            jsonfile.writeFile(file, JSON.stringify(x), error => {
                console.log(error);
            });
        } else {
            const x = JSON.parse(data);
            x.data.push(post);
            const y = JSON.stringify(x);
            jsonfile.writeFile(file, y, e => {
                console.log('Error? ' + e);
            });
        }
    });
}
ghost commented 5 years ago

If you have a very large file where it's not feasible to constantly reread the json to push a new object what you can do is just add commas to the string and then change the file extension.

`rl.on("line", function(line) { var str = line; var slug = str.split("{").shift();

const content = R.replace(slug, "", str) + ","; fs.appendFileSync(file, content); `