Converting Plain Text into Json Using Javascript

I am struggling to convert a lengthy list into a JSON or JavaScript object using JavaScript. Despite searching online, I have not been able to find a suitable solution.

Afghanistan- 132
South Africa - 7560
Albania - 175
Germany - 230
Andorra - 370

This is just a snippet of the complete list, which is too long to manually convert.

The desired output after conversion should resemble this:

[
    {
       "id": 132,
       "country_name":"Afghanistan"
    },
    {
       "id": 7560,
       "country_name":"South Africa"
    },
    {
       "id": 175,
       "country_name":"Albania"
    },
    {
       "id": 230,
       "country_name":"Germany"
    },
    {
       "id": 370,
       "country_name":"Andorra"
    }
 ]

Answer №1

Begin by breaking down the plaintext list using the newline character, resulting in an array of strings such as ["Afghanistan- 132", "South Africa - 7560", ...].

Subsequently, iterate through this list and separate each string to extract the content before and after the dash.

Creating an object within each iteration will produce an array of objects, with any extra whitespace removed from the split values.

To convert this into a usable JSON string, simply employ JSON.stringify() on the transformed data.

const stringList = `Afghanistan- 132
South Africa - 7560
Albania - 175
Germany - 230
Andorra - 370`

const mappedList = stringList.split("\n").map(item => {
    const splitItem = item.split('-');
    return {id: splitItem[1].trim(), country_name: splitItem[0].trim()}
});

const jsonString = JSON.stringify(mappedList);

console.log(jsonString);

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

Even in report-only mode, Content Security Policy effectively blocks the execution of inline scripts

Currently, I have implemented a Content Security Policy (CSP) in 'Content-Security-Policy-Report-Only' mode with a specified report-uri. There is an inline JavaScript code running on the page that the CSP restricts. My initial expectation was tha ...

Signs that indicate you have reached the bottom of the page

Wondering how they achieve that cool effect on where the top line appears with a new logo when you scroll down? Is it done using a jQuery trick? How can you determine when a person has scrolled down a certain amount of pixels and then show them new HTML ...

JavaScript doesn't pause for the data to come back, resulting in an undefined value

When I call the function "classTableData" on a button click, my allData variable becomes undefined. The problem seems to be that it processes the next line of code without waiting for the results, causing allData to remain empty. Can anyone provide some ...

Differences in accessing the previous state between React's useCallback and useState's setState(prevState)

It has come to my attention that useCallback functions recreate themselves when their dependencies change, acting as a sort of wrapper for memoizing functions. This can be particularly useful for ensuring access to the most up-to-date state in useEffect ca ...

What is the process for loading a font file in Vue.js and webpack?

I've done a lot of research, but I couldn't find any links that show me exactly how to add fonts in VueJS. This is the method I'm using to import the font in my LESS file: @font-face { font-family: "Questrial"; src: url("../../fonts/Que ...

Is it possible to leverage specific client-side Javascript APIs on the server-side?

Exploring APIs designed for web browsers that require their .js code to return audio streams. In a broader sense, these APIs provide byte streams (such as audio) for playback in the browser. Is it possible to use these APIs in server-side Javascript frame ...

Using Angular JS for Traditional Multi-page Websites

Lately, I've been diving into Angular 2 and I have to admit, it's an impressive framework for building single-page applications. But here's the thing - how would one go about integrating Angular with a traditional website (maybe using codei ...

Enhancing functionality in Javascript by employing prototype descriptor for adding methods

Code: Sorter.prototype.init_bubblesort = function(){ console.log(this.rect_array); this.end = this.rect_array.length; this.bubblesort(); } Sorter.prototype.init = function(array,sort_type){ this.rect_array = array; this.init_bubblesort(); } Wh ...

Converting Dynamo DB stream data into Json format

I need to convert the DDB stream message into a standard JSON format. To achieve this, I am using unmarshalleddata = aws.DynamoDB.Converter.unmarshall(result.NewImage); where result.NewImage is { carrier: { S: 'SPRING' }, partnerTransacti ...

Using PHP to retrieve JSON data

Looking to extract information from the json data found at Take for instance, if I am interested in retrieving the name "Bulbasaur," I have implemented the following code: <?php $file = file_get_contents("http://mattrb.com/txt.txt"); $json = jso ...

The raycaster in Three.js seems to be having trouble selecting the correct object

Hey everyone, I'm currently working on selecting objects using a raycaster and I want to change the material of the first selected object. Everything works smoothly until I pick the object - when I select the first element, only one object changes. I ...

jquery persistently selects element even after altering the class

Having an issue with a button that needs to change its function after meeting a certain condition. I am attempting to select the button by its class, remove that class when the condition is met, add a new class, and then perform another action. However, i ...

JQuery was partially activated

Having just started using JQuery, I wanted to create a button that can dynamically change the colors defined in the CSS between blue and red when clicked, as well as updating the text displayed on the button. The draggable() function is working properly, ...

What is the best way to retrieve the value from a PHP request?

I am encountering an issue with a multiselect form field named properties[]. When I attempt to retrieve the values in my controller using dd($request->get('properties')), it gives me ["1,2"]. However, trying to access the first ele ...

Dynamically loading components within an Angular application

I am tasked with displaying different components at specific times by iterating through them. Below is an example of how I have attempted to achieve this. The components I can use are determined by the server. <ngb-tabset [activeId]="1"> ...

Could there be any issues with the structure of my mongoose schema?

I've been stuck for 3 hours trying to solve this problem. I can't seem to retrieve any data from my document. var mongoose = require('mongoose'); var Schema = mongoose.Schema; var accountSchema = mongoose.Schema({ username: String ...

Angular facing problems with tracking comment counts in Disqus

After successfully setting up the Disqus comments system on my Angular website following the guide at , everything was working fine. However, when attempting to add the Disqus comment count system to my homepage using the code provided at , I encountered a ...

The alert feature seems to be malfunctioning. I attempted to use an external script file with the code "alert('hello world');" but it did not produce the desired alert

<html> <head> <meta charset="utf-8"> <script scr ="lecture01.js"></script> </head> <body> this is a simple html page </body> The alert function seems to be malfunctioning. I included "alert("hell ...

Can you explain how I can declare a variable to store a scraped element in Puppeteer?

const puppeteer = require('puppeteer'); (async () => { const browser = await puppeteer.launch({ headless: false, defaultViewport: null }) const page = await browser.newPage() await page.goto('https://www.supre ...

Ways to retrieve all elements based on their class names?

What is the equivalent of using $('.class') in JQuery to get all elements by class name with pure JavaScript? ...