What is the method for adding line breaks to a JSON file?

I've been developing a Discord bot and I'm currently storing currency values in a json file. The functionality is working smoothly, but the issue I'm facing is that it's adding them to the json file in a single line which makes it difficult to read.

Here's the code snippet:

                
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 here's how the current json output 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 prefer the json format to be structured like this:

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


Answer №1

Have you taken a look at the documentation for the jsonfile library?

jsonfile.writeFileSync(dataFile, jsonData, { spaces: 2 })

Answer №2

If you're searching for a way to neatly format your JSON data, I have a suggestion.

Check out this resource that explains how you can achieve this using the JSON.stringify() function with the spaces option.

Simply make this adjustment in your code:

jsonfile.writeFileSync(balance, json)

Change it to:

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));

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Ways to adjust the color of a cell in a table

I am working on customizing a table in my website where I need to change the color of a single cell in each row, similar to the example shown in this image: Here is the HTML code that I have implemented so far: <table class="table table-hover t ...

How can one restrict the display of fields in the Meteor aldeed tabular package?

How can I restrict certain data from being displayed in an aldeed tabular datatable? For instance, if my collection includes attributes A, B, C, D and attribute C contains sensitive information that should not be published, is there a way to prevent it fro ...

Trouble arises when attempting to showcase document fields in MongoDB

As a beginner in programming, I am putting in my best effort to figure things out on my own. However, I seem to be stuck without any guidance. I am attempting to display all products from the mongoDB based on their brand. While I have successfully set up a ...

Explore the search bar with functional filtering for JSON items

I'm currently working on creating a dynamic filter bar integrated with a search functionality. My data is stored in JSON format, including details such as artist name, title, source, and more. Despite successfully retrieving results through console.lo ...

Struggling with making react-hook-form correctly validate an email address

I've been struggling for a long time to make this validation work correctly, but it seems impossible. I even added some text at the bottom to display an error message related to the email, but it always shows no error, regardless of the situation. Ed ...

Retrieving the value of a specific property nested within a JSON object using basic JavaScript

Hey there! Thanks for taking the time to check out my question. I'm diving into JavaScript and I've hit a roadblock trying to solve this particular problem: I'm looking to extract the value of a property nested within a JSON object under a ...

What is the best way to pick out specific passages of text

I'm attempting to create an autocomplete feature where the data is displayed in a div below the text box as the user types. While this typically involves ajax, I've simplified the approach without using jQuery autocomplete. Once the text appears ...

When using jQuery without $.ajax, the combination of $.POST and json functions will return "null" when retrieving data from PHP's json_encode

Although I am writing for the first time, I have been a part of this community before. I decided to post my query here because none of the similar questions seemed to offer a clear solution to my specific issue. I am currently working on a tic-tac-toe gam ...

Guide on how to retrieve server error responses in javascript using axios

I am currently using axios to send form data to a Laravel backend. While I can easily access the response upon success, I am facing difficulties retrieving the error response. In my browser's developer tools, under network > response, I see the follo ...

What is a workaround for sending a large/multi-part JSON object without adjusting the maxJsonLength setting?

I'm facing an issue in my C# web application where I receive a JSON object from a WebMethod and it exceeds the maximumJSONLength, resulting in: InvalidOperationException: The length of the string exceeds the value set on the maxJsonLength property. ...

Using Vue.js to dynamically append varying inputs upon user interaction

When I select an option, I want to display different types of inputs based on the selected option. For Example: Select input -> show input fields Select textarea -> show text areas Select boolean -> show radio buttons The Code This is where I choose ...

Encountering a ReferrenceError when utilizing jQuery with TypeScript

After transitioning from using JavaScript to TypeScript, I found myself reluctant to abandon jQuery. In my search for guidance on how to integrate the two, I came across several informative websites. Working with Visual Studio 2012, here is my initial atte ...

unable to respond when clicking an angularjs link

I'm facing an issue where I can't get a link to respond to click events in AngularJS. When I click on the anchor link, nothing happens. Here is a snippet of the AngularJS script: <script data-require="<a href="/cdn-cgi/l/email-protection" ...

Ensuring Node.js backend JavaScript waits for completion of my bash script before proceeding

Running three bash commands through a Node.js code snippet. Here's a portion of the script: exec(str, function(error, stdout, stderr){ console.log('stdout:'+stdout); console.log('stderr:'+stderr); if(error!=null){ ...

Exploring Material UI: Customizing the styling of components within TablePagination

Is it possible to customize the styling of buttons within the actions panel of the TablePagination component? import { withStyles } from '@material-ui/core'; import MuiTablePagination from '@material-ui/core/TablePagination'; const st ...

What are the ways to enable VS Code's Intellisense to collaborate with AngularJS's injected services?

Hey, I've been trying to get Visual Studio Code to provide me with its intellisense for my unique framework (not Angular) app's services. Although I managed to get the standard type for such frameworks, I'm struggling to find a solution for ...

Customizing Drop Down Button in React Material-UI with Conditions

Trying to figure out how to dynamically populate the second MUI dropdown based on the selection from the first dropdown. Currently, I have both dropdown lists hardcoded. const [queryType, setqueryType] = React.useState(''); const [subCategory, se ...

callback triggering state change

This particular member function is responsible for populating a folder_structure object with fabricated data asynchronously: fake(folders_: number, progress_callback_: (progress_: number) => void = (progress_: number) => null): Promise<boolean ...

Refreshing a section of a webpage using AJAX and PHP

After creating a RESTful API in PHP, I can easily register information by accessing the address . This registration process involves sending a POST request. Below is an overview of my method: File: api.php <?php /* File: api.php */ private function ...

Is there a way to seamlessly integrate typeahead.js with jquery.validate?

Currently, I have a website built on ASP.NET MVC 5 which utilizes jQuery validation (specifically 'jquery.validate.js' in the MVC project template). My goal is to implement type-ahead functionality using 'typeahead.js' on an input field ...