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

Showcasing the information stored within my li element, I am able to access and view the data through my console

I want to showcase the data in the browser Upon hitting the api call, I retrieve the data in my console. The challenge lies in displaying the data within my li tag. Below are snippets of my relevant code and the entire code can be found in the gist links p ...

What is the best way to assign default values when destructuring interfaces within interfaces in TypeScript?

My goal here is to create a function that can be used with or without arguments. If arguments are provided, it should work with those values; if not, default values should be used. The issue I'm facing is that although there are no TypeScript errors ...

Refresh the datatable using updated aaData

How do I automatically update the Datatable with new Json data? POST request is used to receive data, which is then sent to the LoadTable function in order to populate the datatable. function initializeTable(){ $("#submitbutton").on( 'click', ...

JavaScript: The Battle of Anonymity - Anonymous Functions vs Helper

I'm currently grappling with a piece of functional style code that is featured in the book Eloquent Javascript: Here's the issue I'm facing: When I have the count() function passing an anonymous function to reduce(), everything seems to wor ...

What is the best way to iterate through array elements with AngularJS?

I am looking to showcase array values using the ng-repeat directive, and then call the getimage function with itemid and photoidlist in order to retrieve the image URL. The JSON data that I have is as follows: $scope.productslist = { "json": { "re ...

Avoiding page refresh while utilizing the ng5-slider component in Angular

I am currently working with an ng5-slider that has a customizable range from 0 to 1000. However, I have encountered an issue when adjusting the slider at the bottom of the page - it refreshes and automatically takes me back to the top of the page. I would ...

Exploring the gridview with JQuery to iterate through and verify if any checkboxes have been selected

I am currently working on a jQuery-based application. In this application, I have an ASP.net GridView that contains checkboxes in each row. My goal is to determine whether any of the checkboxes are checked or not. Below is the code snippet where I loop thr ...

When attempting to send emails, SendGrid encounters an error and fails to provide an error code

Earlier today, I successfully sent out a series of emails using SendGrid. It was quite a large number of emails, as I needed to create multiple user accounts with attached email addresses. Thankfully, everything went smoothly and all the emails were delive ...

Tips for optimizing the placement of div elements for top advertisements on Amazon's website

I'm looking to overlay some divs on top of Amazon.com ads, similar to the image above. This is part of a personal project where I need to position these divs precisely over the ads. To achieve this effect, I've been using getBoundingClientRect t ...

Cookie Strategy for Managing Popups Site-wide

Below is a script that will trigger a popup after 60 seconds of page load. This script also creates a cookie to prevent the popup from appearing more than once. The cookie expires when the user's session ends. However, the popup only appears on the e ...

What could be causing the error with firebase Sign In in next.js?

I set up a sign in page to enter email and password for Firebase authentication. The sign up process works fine, but I'm encountering an issue with the sign in functionality. 'use client' import { useState } from 'react'; import { ...

Is it possible to implement CSS code from a server request into a React application?

With a single React app that hosts numerous customer websites which can be customized in various ways, I want to enable users to apply their own CSS code to their respective sites. Since users typically don't switch directly between websites, applying ...

Failed Cross-Origin Request Sharing in AngularJS 1.4

I'm currently working with AngularJS version 1.4.3 and here is the code snippet I am using: angular .module('app', []) .run(run); function run($http) { a = $http({ method: "GET", url: 'http://127.0.0 ...

I'd like to know what sets next/router apart from next/navigation

Within Next.js, I've noticed that both next/router and next/navigation offer a useRouter() hook, each returning distinct objects. What is the reasoning behind having the same hook available in two separate routing packages within Next.js? ...

Interactive Table - Enhance Your Searching Experience with jQuery

Recently, I've been tackling a Live Search solution for my data table. Success! When searching for Jim, everything works flawlessly. ...

Creating a 2D array matrix in JavaScript using a for loop and seamlessly continuing the number count onto the next row

I'm attempting to create a 2d matrix with numbers that continue onto the next row. var myMatrix = []; var rows = 5; var columns = 3; for (var i = 0; i < rows; i++) { var temp = 1; myMatrix[i] = [i]; for (var j = 0; j < columns; j++) ...

Utilize Vuex mutators within route navigation guards

Hey there, I'm currently working on an app using Laravel and VueJS. To restrict certain routes, I've implemented navigation guards. However, I'm facing an issue where I need to access Vuex mutators to determine if the current user is logged ...

Is there a way to inject C++ text into an input field on a webpage using QWebEngine?

I want to integrate a website with QWebEngine to manipulate input commands using Qt's event filters and more. The specific website I am working with requires a username/email and password, and I aim to manage the input of this text on my end. This inv ...

The user removal process is not functioning properly

I'm encountering an issue in my Angularfire project while trying to remove a user. The email and password are being passed correctly, but the method responsible for user removal isn't getting executed. Below is the snippet of code from my Authent ...

What is the best way to isolate the elements from the specified dictionary that contain valid data?

I need to extract only the data for Flipkart from this array and create a new array containing just that information. json = [ { "amazon": [] }, { "flipkart": { "product_store": "Flipkart", ...