A tool developed in Javascript that allows for the conversion of .ini files to .json files directly on the client

Does anyone know of a JavaScript library that can convert .ini files to .json files on the client-side? I checked out this library, but it doesn't meet my requirements.

Here is an example of an .ini file:

[Master_Settings:1]
Model Name=RC-74DL
IP Address=192.168.1.39
Port=50000
[Device_Ports:1]
[Slave_Settings:2]
ConfigurationfilePath=C:\Users\name\Documents\K-Cssig2\Devices\RC-63D.xml
Button Label1=
[Device_Ports:2]
ADIO Mode 1 = DI
ADIO Mode 2 = DI
[Slave_Settings:11]
Model Name = Test 3
Desription=
ConfigurationfilePath=Devices\Test 3.xml
Button Label1=
Button Label2=
[Device_Ports:11]
ADIO Mode 1 = DI
ADIO Mode 2 = DI

[Serial:1:6]
Main Display=True
Default Port Description=MX660
User Port Description=MX660
Driver Name=BenQ MX660 A
Device_On_Command=N/A
Device_Off_Command=N/A
IsPowerQuery=False
IsLampQuery=False

I need to convert this to .json format. Any suggestions?

Answer №1

Working with strings is the main focus here, and there's no need to rely on an external library.

For those interested, here's a suggestion using ES6 (the inifile data is embedded within a hidden div in the HTML):

( () => {
    let ini2Obj = {};
    const keyValuePair = kvStr => {
    const kvPair = kvStr.split('=').map( val => val.trim() );
        return { key: kvPair[0], value: kvPair[1] };
    };
    const result = document.querySelector("#results");
    document.querySelector( '#inifile' ).textContent
    .split( /\n/ )                                        // split lines
        .map( line => line.replace( /^\s+|\r/g, "" ) )     // clean up whitespace
        .forEach( line =>  {                               // transform into object
            line = line.trim();
            if ( line.startsWith('#') || line.startsWith(';') ) { return false; }
            if ( line.length ) {
              if ( /^\[/.test(line) ) {
                this.currentKey = line.replace(/\[|\]/g,'');
                ini2Obj[this.currentKey] = {};
              } else if ( this.currentKey.length ) {
                const kvPair = keyValuePair(line);
                ini2Obj[this.currentKey][kvPair.key] = kvPair.value;
              }
            } 
          }, {currentKey: ''} );
    
    result.textContent += 
    `**Check: ini2Obj['Slave_Settings:11'].ConfigurationfilePath = ${
          ini2Obj['Slave_Settings:11'].ConfigurationfilePath}`;
    
    result.textContent += 
      `\n\n**The converted object (JSON-stringified)\n${
      JSON.stringify(ini2Obj, null, ' ')}` ;
})();
.hidden {display: none}
<div class="hidden" id="inifile">
    # this is a comment line
    [Master_Settings:1]
    Model Name=RC-74DL
    IP Address=192.168.1.39
    Port=50000
    
    [Device_Ports:1]
    
    [Slave_Settings:2]
    ConfigurationfilePath=C:\Users\name\Documents\K-Cssig2\Devices\RC-63D.xml
    Button Label1=
    
    ; this is a comment line too
    [Device_Ports:2]
    ADIO Mode 1 = DI
    ADIO Mode 2 = DI
    
    [Slave_Settings:11]
    Model Name = Test 3
    Desription=
    ConfigurationfilePath=Devices\Test 3.xml
    # Note: no labels here
    Button Label1=
    Button Label2=
    
    [Device_Ports:11]
    ADIO Mode 1 = DI
    ADIO Mode 2 = DI
    
    [Serial:1:6]
    Main Display=True
    Default Port Description=MX660
    User Port Description=MX660
   
    # Note: empty lines are ok
    Driver Name=BenQ MX660 A
    Device_On_Command=N/A
    Device_Off_Command=N/A
    IsPowerQuery=False
    IsLampQuery=False
</div>

<pre id="results"></pre>

Experience it in action at this jsFiddle

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

Tips for incorporating WinBox JS into Angular applications

I've been experimenting with the WinBoxJS JavaScript library, and I'm familiar with using it in plain JS. However, I'm now attempting to integrate it into my Angular project. Can anyone guide me on how to achieve this? https://www.npmjs.com/ ...

Why is "undefined" being used to alert an ajax call response?

I am encountering an issue with a returned value from an AJAX request. The web method being referenced returns a boolean value of true or false. However, when attempting to access this value outside the AJAX method, I am receiving an "undefined" message :? ...

Verify the input in text fields and checkboxes using JavaScript

I'm in the process of creating a complete "validate-form" function, but there are still a couple of things missing: Ensuring that the Name field only allows alphabetical characters and white spaces Validating that at least one checkbox is selected, ...

What is the best way to combine API calls using rxJs subscribe and map in Angular?

Currently, I am executing multiple API requests. The first one is responsible for creating a User, while the second handles Team creation. Upon creating a User, an essential piece of information called UserId is returned, which is crucial for the Team cre ...

I'm having trouble with my dataTable creation using JQuery. Can anyone help me troubleshoot?

I've attempted various methods to make this work. Here's what I'm importing: <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"> </script> <script type="text/javascript" src="https://cdn.datatabl ...

Convert your Airbnb short link into the full link

I am currently developing an application that utilizes Airbnb links as part of its input. So far, I have identified two types of links: Long form, for example: . These are commonly used on desktop. Short form, such as: . These shorter links are often shar ...

Add navigation dots to the slider in order to align them with the specified div element

Visit this JSFiddle link for the code <html> <link href="./style.css" rel="stylesheet" type="text/css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script&g ...

data-cy appears in the DOM structure, yet remains unseen

I'm seeking some clarity on how to effectively use Cypress. While writing end-to-end tests, I encountered a failed test due to the element not being visible. A helpful answer I found assisted me in resolving this issue by clicking an element that was ...

How to Eliminate the Border on the Final Item within a React List

Hi everyone, I need help with removing the border of the last item in an unordered list when the list reaches a certain size. I initially tried this: document.querySelector('.employee-list-item:last-child').style.border = "none"; However, I enc ...

Tips for transferring properties from one React component to another React component

I need to figure out how to activate a button in a modal when text is entered into an input field. The form is part of a different class and is utilized within a parent class. How can I pass an onChange method to my form component? Check out the code for ...

Error: The property value supplied for the calc() function is invalid

<App> includes both <Header> and <Content> components. I am attempting to calculate the height of <Content>, which is equal to the height of <App> minus the height of the header. // App.js import { useStyles } from "./Ap ...

Experiencing difficulties with null arrays while processing JSON data

Encountering an issue while converting Json properties to C# properties. The precondition is that an array, which most of the times will be null, but if not null, it will have no entries. The same condition applies to List values (KvpDTO is essentially a d ...

Troubleshooting Problems with POST Requests in ExpressJS

Currently, I am working on developing a feature in NodeJS that allows users to upload files. However, I am encountering difficulties while attempting to make a simple POST request. In my index.ejs file, I have written code that generates a form and initia ...

Can express middleware be tailored for each individual handler within the same route path?

I am seeking to create distinct routes under an /api path with varying middleware handlers, each allowing for different authentication methods. My initial approach was to nest these API routes under separate instances of the Router object using Express: c ...

input value does not change when the "keyup" event is triggered

I'm encountering an issue with the code below. The code is for a simple To Do app using Javascript. I followed a tutorial step by step, but my app isn't functioning as expected. When I press the enter key, the input value should be added to the l ...

Having trouble displaying my klout score with ajax

I'm attempting to showcase a Klout score on a webpage Here's my code: <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script> var settings = { "url": "http://api.klout.co ...

React Datepicker on Safari: A seamless way to pick dates

While working on my application, I encountered an issue with the Form.Input functionality from Semantic UI React library. I am using it to insert dates and found that it displays a date-picker on Chrome and Firefox but not on Safari. I attempted to use the ...

What specific portion of the code will be transformed into a virtual DOM?

As a newcomer to the virtual DOM concept, I have been pondering how it functions over the past few days. Let's envision that I have integrated a simple template engine like twig into my project, and I am utilizing vue.js as my chosen javascript frame ...

How to trigger a file download instead of opening it in a new tab when clicking on a txt or png file in AngularJS

After retrieving my file URL from the backend API, I am trying to enable downloading when the user clicks a button. Currently, the download function works smoothly for Excel files (`.xlsx`), but for text (`.txt`) files or images (`.jpeg`, `.png`), it only ...

Unable to execute ajax on dom ready in Internet Explorer 9

Here is some code that needs to be executed on DOM ready without any user interaction: if($.browser.msie){ console.log("Using getJSON"); $.getJSON(baseUrl,function(){ alert('hi'); }); }else{ setTimeou ...