Skip to content

Instantly share code, notes, and snippets.

@carlynorama
Created February 4, 2023 01:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save carlynorama/767a94a73523ab6fed83370da4b61d0e to your computer and use it in GitHub Desktop.
Save carlynorama/767a94a73523ab6fed83370da4b61d0e to your computer and use it in GitHub Desktop.
Working With JSON in JavaScript
import { readFile, writeFile } from 'fs/promises';
import { readFileSync, writeFileSync } from 'fs';
function writeToJson(path, data, rewrite = false) {
let old_data = readFileSync(path);
if (old_data.length == 0 || rewrite == true) {
writeFileSync(path, JSON.stringify(data, null, 4));
return;
}
let json_obj = [JSON.parse(old_data)]; // without brackets it reverts an error
json_obj.push(data);
writeFileSync(path, JSON.stringify(json_obj, null, 4));
}
const addToStatusFile = async (data, fileName) => {
//TODO: if file does not exist create an empty file with []
let fileContents = await readFile(fileName, { encoding: 'utf8' });
let fileObjects = JSON.parse(fileContents);
fileObjects.push(data);
await writeFile(fileName, JSON.stringify(fileContents, null, 2), { encoding: 'utf8' });
};
const testLoad = async (fileName) => {
let fileContents = await readFile(fileName, { encoding: 'utf8' });
let fileObjects = [JSON.parse(fileContents)];
if (fileObjects.length > 0) {
console.log(fileObjects[0].id);
fileObjects.push(fileObjects[0]);
await writeFile(fileName, JSON.stringify(fileObjects, null, 2), { encoding: 'utf8' });
}
else {
console.log("not an array");
let newArray = [];
newArray.push(fileObjects);
console.log(newArray);
}
// fileObjects.push(data);
// await writeFile(fileName, JSON.stringify(fileContents, null, 2), { encoding: 'utf8' });
};
const addToStatusFile2 = async (data, fileName) => {
let fileContents = await readFile(fileName, { encoding: 'utf8' });
let fileObjects = JSON.parse(fileContents);
let arrayToUse = [];
if (fileObjects.length > 0) {
console.log(fileObjects[0].id);
arrayToUse = fileObjects;
}
else {
console.log("not an array");
arrayToUse.push(...fileObjects);
}
// fileObjects.push(data);
// await writeFile(fileName, JSON.stringify(fileContents, null, 2), { encoding: 'utf8' });
};
testLoad("musings.json");
import { readFile, writeFile } from 'fs/promises';
import { readFileSync, writeFileSync } from 'fs';
function writeToJson(path, data, rewrite = false) {
let old_data = readFileSync(path);
if (old_data.length == 0 || rewrite == true) {
writeFileSync(path, JSON.stringify(data, null, 4));
return;
}
let json_obj = [JSON.parse(old_data)]; // without brackets it reverts an error
json_obj.push(data);
writeFileSync(path, JSON.stringify(json_obj, null, 4));
}
const addToStatusFile = async (data, fileName) => {
//TODO: if file does not exist create an empty file with []
let fileContents = await readFile(fileName, { encoding: 'utf8' });
let fileObjects = JSON.parse(fileContents);
fileObjects.push(data);
await writeFile(fileName, JSON.stringify(fileContents, null, 2), { encoding: 'utf8' });
};
const testLoad = async (fileName) => {
let fileContents = await readFile(fileName, { encoding: 'utf8' });
let fileObjects = [JSON.parse(fileContents)];
if (fileObjects.length > 0) {
console.log(fileObjects[0].id);
fileObjects.push(fileObjects[0]);
await writeFile(fileName, JSON.stringify(fileObjects, null, 2), { encoding: 'utf8' });
}
else {
console.log("not an array");
let newArray = [];
newArray.push(fileObjects);
console.log(newArray);
}
// fileObjects.push(data);
// await writeFile(fileName, JSON.stringify(fileContents, null, 2), { encoding: 'utf8' });
};
const addToStatusFile2 = async (data, fileName) => {
let fileContents = await readFile(fileName, { encoding: 'utf8' });
let fileObjects = JSON.parse(fileContents);
let arrayToUse = [];
if (fileObjects.length > 0) {
console.log(fileObjects[0].id);
arrayToUse = fileObjects;
}
else {
console.log("not an array");
arrayToUse.push(...fileObjects);
}
// fileObjects.push(data);
// await writeFile(fileName, JSON.stringify(fileContents, null, 2), { encoding: 'utf8' });
};
testLoad("musings.json");
{
"id": "109803445656514120",
"createdAt": "2023-02-03T23:40:15.608Z",
"inReplyToId": null,
"inReplyToAccountId": null,
"sensitive": false,
"spoilerText": "",
"visibility": "public",
"language": "en",
"uri": "https://social.cozytronics.com/users/tipsyrobot/statuses/109803445656514120",
"url": "https://social.cozytronics.com/@tipsyrobot/109803445656514120",
"repliesCount": 0,
"reblogsCount": 0,
"favouritesCount": 0,
"editedAt": null,
"favourited": false,
"reblogged": false,
"muted": false,
"bookmarked": false,
"pinned": false,
"content": "<p>But I&#39;m just rambling, not caring if any of it actually gets through...</p>",
"filtered": [],
"reblog": null,
"application": {
"name": "Tipsy Robot",
"website": null
},
"account": {
"id": "109802669824115839",
"username": "tipsyrobot",
"acct": "tipsyrobot",
"displayName": "tipsyrobot",
"locked": false,
"bot": true,
"discoverable": false,
"group": false,
"createdAt": "2023-02-03T00:00:00.000Z",
"note": "",
"url": "https://social.cozytronics.com/@tipsyrobot",
"avatar": "https://social.cozytronics.com/avatars/original/missing.png",
"avatarStatic": "https://social.cozytronics.com/avatars/original/missing.png",
"header": "https://social.cozytronics.com/headers/original/missing.png",
"headerStatic": "https://social.cozytronics.com/headers/original/missing.png",
"followersCount": 0,
"followingCount": 1,
"statusesCount": 11,
"lastStatusAt": "2023-02-03",
"noindex": false,
"emojis": [],
"fields": []
},
"mediaAttachments": [],
"mentions": [],
"tags": [],
"emojis": [],
"card": null,
"poll": null
}
@todbot
Copy link

todbot commented Feb 4, 2023

Here's how I might do it:

import { readFile, writeFile } from 'fs/promises';

const appendObjectToFile = async(myobj,filename) => {
    let objs = [];  // in case there are none
    // attempt to read and parse file, if fail, we have new objs array above
    try {
        let contents = await readFile(filename, { encoding: 'utf8' });
        objs = JSON.parse(contents)
    } catch (e) {
        console.log("appendObjectToFile error:",e.message);
        console.log("starting new file");
    }
    // add to object array
    objs.push(myobj)
    // save combined obj array to file
    await writeFile(filename, JSON.stringify(objs, null, 2), { encoding: 'utf8' });
};

console.log("writing first object")
let myobj1 = { name:'Maxipants', alignment:"mostly evil"}
await appendObjectToFile(myobj1, "catlog.json")

console.log("writing second object")
let myobj2 = { name:'Crookshanks', alignment:"chaotic hunger"}
await appendObjectToFile(myobj2, "catlog.json")

console.log("writing third object")
let myobj3 = { name:'Claret', alignment:"sproingy neutral"}
await appendObjectToFile(myobj3, "catlog.json")

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment