Transform a text file with data stored in key-value format into JSON format

Imagine having a text file with data such as:

[ key = 1542633482511430199, value=>>>BasicData:isConfirmAndOrder=0,brmRequestId=BR-2018-0000124,requestType=batch,projectName=Automation_Product_By_Admin,projectId=PRJ-2018-0000477,department=Global Packaging] 

What is the best way to convert this into JSON format?

I am looking for a solution preferably in JavaScript, but I am open to other languages as well.

Answer №1

If you want to achieve this task, the key is performing a series of replacements, aided by a helper function:

String.prototype.replaceAll = function(search, replacement) {
    var target = this;
    return target.replace(new RegExp(search, 'g'), replacement);
};

Next, execute the replacements and utilize JSON.parse:

JSON.parse(
'[ key = 1542633482511430199, value=>>>BasicData:isConfirmAndOrder=0,brmRequestId=BR-2018-0000124,requestType=batch,projectName=Automation_Product_By_Admin,projectId=PRJ-2018-0000477,department=Global Packaging]'
.replace(':', ':{').replace(']', '}}')
.replace(':', ':{').replaceAll("=", ':"')
.replaceAll(",", '",')
.replace(':"', ":")
.replace('[', '{')
.replace("}}", '"}}}')
.replace('",', ",")
.replace('>>>', '{')
.replace('{{', '{')
.replace('value:"', "value:")
.replace("=", ":")
.replace('key :', '"key" :')
.replace('value:', '"value":')
.replace('BasicData:', '"BasicData":')
.replace('isConfirmAndOrder:', '"isConfirmAndOrder":')
.replace('brmRequestId:', '"brmRequestId":')
.replace('requestType:', '"requestType":')
.replace('projectName:', '"projectName":')
.replace('projectId:', '"projectId":')
.replace('department:', '"department":')
)

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

Error in timing for notifications being dispatched (Java, Android Studio)

When using my app, the user has the option to select a date and time for notifications to be sent out. However, I've noticed that the notifications are not being sent out at the correct time. If I schedule a notification for the same day, it gets sent ...

Deciphering JSON responses from the Bit2Check.com API

I am currently utilizing the Bit2Check.com API to verify emails associated with PayPal accounts. However, when I provide an email address to the API, it returns the following response: {"Paypal":"Linked"} My goal is to extract only the "Linked" part from ...

When it is first activated, the Ajax .load() function will not function correctly

I recently encountered an issue with a tab system that I implemented using the .load function to load content dynamically. The problem arose because the page containing this tab system was loaded via ajax, causing the initial call to the tab function to di ...

Identify the specific button that triggers a JavaScript function

Currently, I am working on an admin page that displays a list of posts using EJS for template rendering engine. <table> <tr> <th>Name</th> <th>Description</th> </tr> <% projects.for ...

The JSON syntax contains an unexpected token

I am encountering an issue with a JavaScript variable named "text" that contains the following value: text={"text":"@RT #Olle_Carly Nuevas filtraciones del iPhone 6: así sería comparado con el Samsung Galaxy S5 y el iPhone 5S: Des... http://t.co/eRuXLS6 ...

This message is designed to validate the form as it is dynamic and

Is there a way to dynamically determine which .input fields have not been entered yet? In the following code snippet, you can observe that if I input data out of sequence, the #message displays how many inputs have been filled and shows the message in sequ ...

Hibernate in conjunction with MySQL is a powerful combination for

I am currently working with a class that has the following fields: @Entity @Table(name = "customers") public class Customer { @Id int id; String name; String items; String when; String where; ... // getters and setters } In my ...

Showing a loading animation inside an HTML element

I have a main webpage that contains several buttons. Each button, when clicked, loads a specific target page as an object within a div on the main page. The "target" refers to the page that will be displayed within the object. <script> .... chec ...

selecting arrays within arrays according to their date values

With an array of 273 arrays, each containing data about a regular season NFL football game, I am looking to categorize the games by week. In total, there are 17 weeks in the NFL season that I want to represent using separate arrays. The format of my array ...

Dynamically parallelizing functions with async and arrays

I have recently integrated the fantastic "async" module by caolan into my Node.js project: Below is a snippet of the code in question: exports.manageComments = function(req, res) { var toDeleteIds = []; var deleteFunctions = []; if (req.body. ...

If the given response `resp` can be parsed as JSON, then the function `$

I was using this script to check if the server's response data is in JSON format: try { json = $.parseJSON(resp); } catch (error) { json = null; } if (json) { // } else { // } However, I noticed that it returns true when 'res ...

Using Node.js to streamline PowerShell command strings

I am having trouble retrieving data accurately using Powershell with Node.js. Despite trying various packages to execute Powershell commands in Node.js and fetch data from the console, I keep encountering the issue of trimmed data. For instance, when I ru ...

The absence of jasmine-node assertions in promises goes unnoticed

Everything seems to be running smoothly with the code below, except for the assertion part. Whenever I run the test using Jasmine, it reports 0 assertions. Is there a way to include my assertions within promises so they are recognized? it("should open sav ...

Attempting to transfer various variables from several windows using AJAX

Is it possible to pass multiple variables from two different windows into the same PHP script? If not, what would be the best approach to take? Thank you. verifyemail.html <script type = "text/javascript" src = "js/js_functions.js"></script> ...

Export generated JSON as a file in Node.js

My server is creating a JSON object/array and I want to send it to the user as a file, not displayed on the browser. How can I achieve this? I'm hesitant about writing it to a file and then utilizing res.sendFile(). Is there a better way to handle th ...

Discovering JSON data embedded within a script tag in an HTML response using Jsoup

Looking for help with extracting JSON content from script tags embedded in an HTML file. I attempted to use Jsoup without success. Can anyone provide guidance on utilizing JSOUP or another library for this task? Thank you in advance. ...

Mobile Mode Issue with Bootstrap 4 Navbar Example

Currently, I am exploring the Bootstrap material and trying to understand how to integrate their content with a jinja2 file that I am preparing for a django project. Upon attempting to copy and paste their example code (specifically this example http://get ...

Android - RelativeLayout - Adjacent Buttons

I am trying to arrange two buttons next to each other in a RelativeLayout that is then included in a LinearLayout, but the outcome is both buttons appearing on top of one another like this: Here is the code I am using: DisplayMetrics displaymetrics = new ...

What is the best way to merge arrays within two objects and combine them together?

I am facing an issue where I have multiple objects with the same properties and want to merge them based on a common key-value pair at the first level. Although I know about using the spread operator like this: const obj3 = {...obj1, ...obj2} The problem ...

Comparing the architecture of two JSON objects in JavaScript without taking into account their actual content

One of the tools I rely on for my projects is a Node.js based mock server that helps me specify and mock API responses from the backend. However, it would be beneficial to have a way to ensure both the backend and frontend are in sync with the specified st ...