Converting text data into JSON format using JavaScript

When working with my application, I am loading text data from a text file:

The contents of this txt file are as follows:

console.log(myData):

### Comment 1
## Comment two
dataone=1
datatwo=2
## Comment N
dataThree=3

I am looking to convert this data to JSON by following these steps:

  • Remove all comment lines (beginning with #) and empty lines
  • Replace all = with :
  • Add quotes to the data attributes to make it look like this
  • Wrap everything inside { }

The resulting JSON would appear as follows:

{
"dataone":"1"
"datatwo":"2"
"dataThree":"3"
}

Is there a quick way to achieve this formatting?

Answer №1

If you're looking for a basic and straightforward solution, how about trying this approach:

const data = myData
  .split('\n')
  .filter(line => !line.startsWith('#') && line.includes('='))
  .map(line => line.split('='))
  .reduce((obj, [key, value]) => {
     obj[key] = value.trim();
     return obj;
  }, {});

const jsonData = JSON.stringify(data);

Limitations

  • There is no support for duplicate keys, although standard JSON libraries also do not allow them.
  • All values will be treated as strings, even numerical values may remain in string format.
  • Error handling has not been implemented for scenarios not covered in the original example text.

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

Jumping Iframe Anchor Link in Src

I'm facing a challenge with an iframe positioned in the center of a webpage. I want to show content from another page within the iframe, but not starting at the very top. To achieve this, I inserted an anchor into the src of my iframe, linked to an a ...

What is the reason for the retrieval of jquery-3.5.1.min.js through the request.params.id expression?

For my school project, I am using Express.js with TypeScript to create a simple app. This router is used for the edit page of a contact list we are developing. It displays the ID of the current contact being edited in the search bar. The problem arises whe ...

Dynamic tag names can be utilized with ref in TypeScript

In my current setup, I have a component with a dynamic tag name that can either be div or fieldset, based on the value of the group prop returned from our useForm hook. const FormGroup = React.forwardRef< HTMLFieldSetElement | HTMLDivElement, React. ...

Do I have to divide the small functions in my Node.js controller into smaller ones?

When signing up users in my controller, do I need to break up the sign-up steps into individual asynchronous calls or is one big asynchronous call sufficient? Each step relies on the previous one: Validate user Create user Create group Add user to group ...

Steps for dynamically loading the correct pane without having to refresh the header, footer, or left navigation

Looking to create a web application using HTML, Bootstrap, and jQuery that includes a header, footer, left navigation, and right pane. The content of the right pane will be loaded from a separate HTML page based on what is clicked in the left navigation. ...

retrieve the checkbox formgroup using the Response API

After following a tutorial on creating dynamic checkboxes, I now need to implement dynamic checkboxes using an API request. In my implementation so far, I have defined the structure as shown below: inquiry-response.ts interface Item { // Item interface ...

Set the parameter as optional when the type is null or undefined

I need to create a function that can take a route and an optional set of parameters, replacing placeholders in the route with the given params. The parameters should match the placeholders in the route, and if there are no placeholders, the params should b ...

worldpay implements the useTemplateForm callback function

My experience with implementing worldpay on my one-page Angular app (Angular 1.x) has been mostly positive. I have been using the useTemplateForm() method to generate a credit card form and retrieve a token successfully. However, I have encountered an issu ...

Issue with the recursive function in javascript for object modification

I have all the text content for my app stored in a .json file for easy translation. I am trying to create a function that will retrieve the relevant text based on the selected language. Although I believe this should be a simple task, I seem to be struggl ...

The issue with ngx-bootstrap-modal is that it fails to interpret HTML elements

In my Angular 5 project, I am implementing ngx-bootstrap-modal. Below is the code I am using to open the modal: this.dialogService.addDialog(PopUpComponent, { title: 'Custom locale', message: "Hello ? " }).subscribe((isConfirmed ...

CodeIgniter encountering a dilemma with session logout functionality

if ($this->Adminmodel->check_credentials($this->input->post('email'), $this->input->post('password')) =="true") { redirect("admin/dashboard"); } ...

Having trouble converting data back to JSON format after using JSON.parse in an ejs file with node and express

I'm retrieving data from an external API on my server, then attempting to pass that data to an ejs file using JSON.stringify(data), and trying to read the data in the ejs file by parsing it with JSON.parse(data). However, I am encountering issues wher ...

Managing conflicting versions of React in a component library created with Webpack and Storybook

My goal is to create a React component library on top of MUI using Storybook and TypeScript. Since Storybook is based on Webpack (which includes SASS files), I'm utilizing Webpack to build the bundle because TSC can't compile those files. Subsequ ...

JS | How can we make an element with style=visibility:hidden become visible?

HTML: <div id="msg-text"><p><b id="msg" name="msg" style="visibility:hidden; color:#3399ff;">This is a hidden message</b></p></div> JS: $('#url').on('change keyup paste', function() { $('# ...

Utilize Reactjs to efficiently showcase a collection of arrays within an object

I am struggling with a JSON file that has nested dropdown mega menu levels and I can't figure out how to map and render multiple levels of arrays and objects to create a tree-like structure. Here is my current JSON Structure: { "megamenu": [ { ...

Why does Chrome keep retrieving an outdated JavaScript file?

Lately, I've been facing a frustrating issue that I just can't seem to figure out. Every now and then, when I update the JavaScript or CSS files for my website hosted on Siteground, Chrome simply refuses to acknowledge the changes. While other br ...

Issue with Material UI Table not refreshing correctly after new data is added

Currently, I am utilizing a Material-UI table to display information fetched from an API. There's a form available for adding new entries; however, the problem arises when a new entry is added - the table fails to update or re-render accordingly. For ...

Updating a div using PHP elements

Currently, I'm using a webcam to capture images for a project related to learning. My goal is to showcase the recently taken photos. After taking a photo, it gets stored in a folder. To display all the collected photos within a <div>, I need to ...

I keep encountering a 404 error page not found whenever I try to use the useRouter function. What could

Once the form is submitted by the user, I want them to be redirected to a thank you page. However, when the backend logic is executed, it redirects me to a 404 page. I have checked the URL path and everything seems to be correct. The structure of my proje ...

Navigating the interface types between Angular, Firebase, and Typescript can be tricky, especially when working with the `firebase.firestore.FieldValue`

I am working on an interface that utilizes Firestore timestamps for date settings. export interface Album{ album_name: string, album_date: firebase.firestore.FieldValue; } Adding a new item functions perfectly: this.album ...