What is the process for transforming this information into JSON format with Javascript?

I have a server response with data that needs to be converted to JSON using JavaScript.

country=Philippines\r\n
countryid=840\r\n
operator=Globe Telecom Philippines\r\n
operatorid=246\r\n
connection_status=100\r\n
destination_msisdn=639358661725\r\n
destination_currency=PHP\r\n
product_list=25,50,150,300,500,1000\r\n
retail_price_list=0.70,1.40,4.10,8.10,13.50,27.00\r\n
wholesale_price_list=0.56,1.10,3.26,6.49,10.80,21.58\r\n
authentication_key=1429269579325\r\n
error_code=0\r\n
error_txt=Transaction successful\r\n

Seeking assistance to convert this data structure into JSON format using JavaScript. Any guidance or pointers would be appreciated.

Answer №1

Give this a try:

function convertStringToJson(inputString) {
   return JSON.stringify(inputString.split('\r\n').
   reduce(function(result, current) {data = current.split('=', 2); 
   result[data[0]] = data[1]; return result;}, {}))
}

Example of how to use the function:

convertStringToJson("country=United States\r\ncountryid=840\r\ntimezone=EST\r\nstate=New York")

Result:

"{"country":"United States","countryid":"840","timezone":"EST","state":"New York"}"

Does this solve your problem?

Answer №2

To efficiently handle this situation, you can extract the string by splitting it at \r\n and then further split it at the = sign to structure it appropriately for JSON formatting. You may find the provided link helpful for reference.

http://www.w3schools.com/js/js_json.asp

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

Unable to make getJSON function properly with CodeIgniter

I'm experimenting with using getJSON to retrieve the most recent data from my database. So far, I've stored it in an array and used json_encode(the array). This method successfully displays the information on the view, but the problem lies in the ...

Query SQL view to extract JSON array's elements and generate a new column

One of the challenges I am facing is working with an SQL Table that has a column containing a JSON array structured like this: [ { "id":"1", "translation":"something here", "value":"value of something here" }, { "id" ...

Updating the footer of a React application using Material UI Grid

Having some trouble customizing the footer in a React Material-UI grid. Refer to the image below for details. Any ideas on how to change the: 1 row selected? Thank you! ...

The PHP function is failing to communicate with jQuery and Ajax

Having trouble with PHP return to jQuery/Ajax functionality, When I try to edit an item, the error message displays even though the success function is executed. On the other hand, when attempting to delete an item, nothing is displayed despite the succes ...

What is the best way to extract a value from a JSON object?

I am having trouble deleting data from both the table and database using multiple select. When I try to delete, it only removes the first row that is selected. To get the necessary ID for the WHERE condition in my SQL query, I used Firebug and found this P ...

Basic math tool using JSP/Servlet combination and Ajax

I have a follow-up question to my previous inquiry on Stack Overflow. I believe this topic deserves its own discussion due to the thorough response I received. My goal is to develop a straightforward calculator using JSP. The calculator will include two t ...

How to properly implement search functionality in a React table?

I recently implemented a search feature for my table in React to filter items fetched from an external API. Instead of making repeated calls to the API on each search, I decided to store the retrieved data in two separate useState hooks. One hook holds th ...

Creating an AngularJS directive specifically for a certain <div> tag

Recently, I began learning angularjs and came across a script to change the font size. However, this script ended up changing all <p> tags on the entire webpage. Is there a way to modify the font size of <p> tags only within the <div class=" ...

What is the process for making an Ajax request in Rails?

I'm attempting to send a variable through jQuery using the POST method, saving it in a controller, and then utilizing that same variable in Rails HTML to query a table. It seems like the variable isn't being passed to the controller. jQuery: v ...

Need a module from the main directory

Imagine having these folders: 'C:\\src' // Main directory. 'C:\\src\\inner1' // Contains 'a.js' 'C:\\src\\inner2\\innermost' // Contains 'b.js' ...

npm update fails to update specific packages

After React was updated to version 0.15 to address the issue of excessive generation of tags, I made the decision to update my project.</p> <p>However, when I ran the command <code>npm update, it only updated to version 0.14.8. Running ...

Learn how to send or submit data using the Form.io form builder

I am currently working on a dynamic drag and drop form builder, and I'm struggling to figure out how to log the data from the form. Below is the component.html file where I am implementing the drag and drop form: <div> <form-builder ...

When organizing data, the key value pair automatically sorts information according to the specified key

I have created a key value pair in Angular. The key represents the questionId and the value is the baseQuestion. The baseQuestion value may be null. One issue I am facing is that after insertion, the key value pairs are automatically sorted in ascending ...

How to separate an array of JSON objects into individual columns using Pyspark

Within my pyspark dataframe, there is a column that appears in the following format: [{key1: value1},{key2:value2}, {key3:value3}, {key4:value4}] Let's label this ColumnY as shown below: ColumnY [{key1: value1},{key2:value2}, {key3:value3}, ...

Strapi: Enhancing User Experience with Unique Passwordless Customization Services

I have been attempting to modify the "passwordless" strapi plugin in order to generate verification codes consisting exclusively of digits. To achieve this, I need to override the createToken function within the plugin's service. Following the instru ...

Encountered a JSON parsing error when trying to import data into MongoDB

I've encountered an issue while attempting to import a json file into MongoDB using Java drivers. The error message I received is as follows: Exception in thread "main" com.mongodb.util.JSONParseException: at com.mongodb.util.JSONParser.read ...

"Make sure to tick the checkbox if it's not already selected,

Could use some assistance with traversing and logic in this scenario. Here is the logic breakdown: If any checkbox in column3 is checked, then check the first column checkbox. If none in column 3 are selected, uncheck checkbox in column1. If column1 ...

The Python/JSON error message is stating that only integers or slices can be used as indices for lists, not

Having battled for hours, I could really use your assistance. Seeking a single result from a JSON response. Here is how the JSON file appears: https://i.stack.imgur.com/FwRzG.png The desired outcome should be "Desnoss," and it should only appear once. dat ...

Tips for converting data to JSON format without the need for an object

I am looking to convert my variables to JSON for the purpose of POSTing the JSON to an external API. I do not want to create a separate model just for serialization of these values. Using a Dictionary is not feasible as the structure is unconventional, su ...

discovering obscured information using jquery

I am working on a code snippet where I need to hide the detailed content for display purposes and only show it during printing: <div> <ul> <li> <span style="font-size: 1.25em;"> <strong> ...