1

I am working on a Discord bot and want to save currency values in a json file. It's working just fine so far, but it's appending them to the json file in one single line and although it is entirely functional, I would like to be able to read it.

This is the code

                let json = jsonfile.readFileSync(balance, { throws: false })

            let newBalance = {}

            for (let i = 0; i < 3; i++) {
                let val = embedJSON.fields[i].value
                val = val.replace(",", "")
                let valSplit = val.split(" ")[1]

                newBalance[`${embedJSON.fields[i].name}`] = valSplit

            }
            json[`${user}`] = newBalance
            jsonfile.writeFileSync(balance, json)

And this is what the json looks like

{"Anth'auwe#0169":{"Cash:":"200","Bank:":"399800","Net Worth:":"400000"},"Layers#0169":{"Cash:":"0","Bank:":"199838","Net Worth:":"199838"}}

If possible, I would like for it to look like this

    {
    "Layers#0169": {
        "Cash": 0,
        "Bank": 0,
        "Net Worth": 0
    },
    "Anth'auwe#0169": {
        "cash": 0,
        "bank": 0,
        "Net Worth": 0
    }
    }

2 Answers2

2

Did you tried to read the doc of jsonfile package ?

jsonfile.writeFileSync(balance, json, { spaces: 2 })

Clem
  • 2,150
  • 15
  • 17
2

I think that you're looking how to pretty save your JSON.

As explained here you can do it the same way the JSON.stringify() function does using the spaces option.

Try changing this line:

jsonfile.writeFileSync(balance, json)

For this one:

jsonfile.writeFileSync(balance, json, {spaces: 2})

const myJSON = {"Anth'auwe#0169":{"Cash:":"200","Bank:":"399800","Net Worth:":"400000"},"Layers#0169":{"Cash:":"0","Bank:":"199838","Net Worth:":"199838"}};

console.log(JSON.stringify(myJSON, null, 2));
Brugui
  • 574
  • 6
  • 20