Transforming text elements into JSON format

My text contains a list of items formatted as follows:

var text = "<li>M3-2200 (da2/M3-2200)</li><li>N3-2200 (da2/N3-2200)</li><li>Picasso (picasso/A500)</li><li>Picasso (picasso/A501)</li><li>Picasso (ventana/A500)</li>..."

I am attempting to generate JSON in the following format:

{
     name: "M3-2200",
     Model: "M3-2200"    
}

I have been trying the code below, but I am encountering an issue with push. Can anyone provide insight on how to correct this?

result ={};
while(text.indexOf("<li>")!== -1){
    var listi = text.substring(text.indexOf("<li>"), text.indexOf("</li>"));
    var model = listi.substring(0, listi.indexOf("(") -1);
    var name = listi.substring(listi.indexOf("("), listi.indexOf(")"));
    var item = {name: name: model : model};
    result.push(item);
    var text = text.substring(text.indexOf("</li>"));
}

Answer №1

Here is an alternative solution that may help you:

var data = "<li>M3-2200 (da2/M3-2200)</li><li>N3-2200 (da2/N3-2200)</li><li>Picasso (picasso/A500)</li><li>Picasso (picasso/A501)</li><li>Picasso (ventana/A500)</li>";
var output = JSON.parse('[' + 
  data.replace(/(<li>|<\/li>| \(|\))/g, function(_, segment){
    switch (segment) {
      case '<li>': return '{"name":"';
      case '</li>': return '},';
      case ' (': return '", "Model":"';
      case ')': return '"';
    }
  }) + '0]').slice(0, -1);

Answer №2

let data = "<li>M3-2200 (da2/M3-2200)</li><li>N3-2200 (da2/N3-2200)</li><li>Picasso (picasso/A500)</li><li>Picasso (picasso/A501)</li><li>Picasso (ventana/A500)</li>";
jsonString = data.trim().replace(/<li>/g,"{\"name\":\"").replace(/ \(/g,"\" , \"model\":\"").replace(/\)\<\/li\>/g,"\"},");
jsonString = "["+jsonString.substring(0,jsonString.length-1)+"]";
console.log(jsonString);

Is the functionality of the code above guaranteed?

Answer №3

It seems like you're asking about a specific output format. Here is an example of the desired result:

[{"brand":"M3-2200 ","model":"da2/M3-2200"},{"brand":"N3-2200 ","model":"da2/N3-2200"},{"brand":"Picasso ","model":"picasso/A500"},{"brand":"Picasso ","model":"picasso/A501"},{"brand":"Picasso ","model":"ventana/A500"}]

To achieve this, you can use the following approach:

var data = "<li>M3-2200 (da2/M3-2200)</li><li>N3-2200 (da2/N3-2200)</li><li>Picasso (picasso/A500)</li><li>Picasso (picasso/A501)</li><li>Picasso (ventana/A500)</li>";
var extractInfo = function (item) {
  var partsArray = /(.+) ?\((.+)\)\<\/li>/.exec(item)
  if(partsArray) return {"brand":partsArray[1], "model":partsArray[2]}
}
var resultData = data.split('<li>')
  .map(extractInfo)
  .filter(function(e){return e != undefined});
console.log(JSON.stringify(resultData));

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

Remove bulleted list from HTML using JavaScript DOM

My task involved deleting the entire "agent" array using the removeChild() function, requiring the id of a <ul> element. However, I faced an issue as I couldn't set the id for the "ul" due to using the createElement() function. //old code < ...

The proper way to insert data in JavaScript and PHP

Hello. I have a new function to add a row in my form. However, I recently added a second input field and I am unsure of how to correctly insert it. Below is my JavaScript code: <script type="text/javascript" src="jquery.js"></script> <scri ...

Place a div element directly into a specific cell within the table

How can I place the following div <div class="inner"> <p>The first paragraph</p> <p>The second paragraph</p> </div> into a specific cell within a table? I am open to using either plain JavaScript or jQuery, althou ...

Exploring the world of REST APIs, the versatility of JSON data formatting,

Is there a recommended method for implementing lazy loading with a REST API? In NHibernate, lazy loading allows the collection of "Address" objects within a "Person" object to be loaded from the database only when accessed. But when returning a JSON objec ...

Executing two distinct SQL queries within one nodejs function

I'm facing an issue with updating two tables in my database - the stockmaster table and the prodstock table. I've been trying to run a query using a function to update both tables simultaneously, but unfortunately, it's not working as expect ...

I'm having trouble figuring out why my Vue method isn't successfully deleting a Firebase object. Can anyone offer some guidance

What I am trying to achieve: I have been struggling to use the remove method from Firebase. I have read the documentation, but for some reason, it is not working as expected. Retrieving data using snapshot works fine, but when I try to delete using the re ...

Format the image to fit within a div container

I'm currently utilizing Bootstrap and am looking to insert some images into my div while ensuring they are all the same size (standardized). If the images are too large (as they typically are), I want to resize them to fit within my div and crop them ...

The canvas texture is not properly aligning with the SphereMesh

I have been experimenting with THREE.js and recently tried using a <canvas> element as a THREE.Texture. After finally successfully mapping the object to the mesh, I noticed that the texture was not wrapping around the SphereGeometry as expected; inst ...

Using ServiceStack to deserialize an array

My goal is to post the following data to my ServiceStack web service: $.ajax({ url: 'http://localhost:8092/profiles', type:'POST', data: { FirstName : "John", LastName : "Doe", Categories : [ "Catego ...

Error: Unable to convert a value of type java.lang.String to a JSONObject in Android

Currently working on an Android app and encountering an error when trying to log in. Unable to find a similar structure with my code. Below are the snippets: LoginActivity.java: -- Code removed for brevity -- DatabaseHandler.java: -- Code removed for ...

Attempting to display a grid of product listings using a Websocket connection and an Express server

Recently, I attempted to create a live table of products using websockets for real-time updates. While I am new to this concept, I decided to upgrade an old project with websockets. Unfortunately, my attempts were unsuccessful, which is why I am seeking he ...

Refreshing the Canvas post-submission

I have created a form that allows users to add notes and sign on a Canvas. However, I am facing an issue with clearing the canvas after submission, as it does not seem to work properly. The rest of the form functions correctly. The goal is to clear both t ...

Each time a new client connects, socket.io replicates the information

Exploring Node.js and socket.io for the first time, I have developed a small application where a table is meant to be displayed in real-time via socket.io when a function is triggered through a websocket (function triggers an "emit"). However, I'm fac ...

Vue watchers capturing original value prior to any updates

When working with Vue.js, we can easily access the value after modification within watchers using the following syntax: watch: function(valueAfterModification){ // ...... } But what about getting the value before it's modified? PS: The official ...

Do back-end routes get activated when the route path in the URL matches, or when a fetch request is initiated from the front-end?

Exploring the contrast between utilizing a fetch API versus directly visiting the URL corresponding to the route path. Consider a backend route structured as follows: let ALL_RESTAURANTS = [ { id: "0b65fe74-03a9-4b37-ab09-1c8d23189273", name: ...

Create an object with an asynchronous function/promise declaration

I have a function that returns an object with different functions that I can use. I want to incorporate promises into these functions for better asynchronous handling. var DATABASE = (function () { var exports = {}; exports.query = function(filter = ...

Having trouble installing sqlite3? Encounter an issue like this: "srcdatabase.cc(35): error C2248: 'Napi::Env::DefaultFini': cannot access private member declared in class 'Napi::Env'"?

Encountering issues while trying to install sqlite3 for a Strapi app I've attempted using yarn to install sqlite3 in various ways, but to no avail. Below is the error log: Error message: Issue with installing sqlite3 when creating a Strapi app (..& ...

Exploring the Depths with a Javascript Canvas Deep Zoom Library

I am faced with the task of creating a detailed zoom mosaic using an HTML5 Canvas Element, consisting of thousands of roughly 512x512 images. However, I am striving to minimize reinventing the wheel in the process. Instead of merging numerous large images ...

Issues with retrieving data from Firestore and storing it into an array in a React

Struggling to fetch data from my firestore and display it on the webpage. Despite trying all possible solutions and searching extensively, I am unable to get it working. When using the code below, nothing appears on the website. However, if I switch to th ...

What occurs when Click events are triggered on an <object> element?

I have set up a div, and inside that container, I embedded an SVG image using object (which I plan to manipulate later...). <div id="click-me"> some random Text <object data="some.svg" /> </div> Next, I added event listeners for t ...