The method of iterating over a string in key-value pairs

How can I efficiently loop through a string and extract key/value pairs? The data is provided to me as a single string using the jstorage plugin.

I attempted to split the string into an array, but the resulting key/values were not as expected.

For example:

"color":"#000000", "font":"12px", "background":"#ffffff",

Answer №1

If the string consistently contains keys and values in double quotes, you can easily convert it to JSON by wrapping it with {...} and parsing it:

// remove trailing comma, it's not valid JSON
var obj = JSON.parse('{' + str.replace(/,\s*$/, '') + '}');

If this pattern does not apply, splitting the string based on commas and colons is a straightforward solution as long as they do not appear within keys or values:

var obj = {},
    parts = str.replace(/^\s+|,\s*$/g, '').split(',');

for(var i = 0, len = parts.length; i < len; i++) {
    var match = parts[i].match(/^\s*"?([^":]*)"?\s*:\s*"([^"]*)\s*$/);
    obj[match[1]] = match[2];
}

Answer №2

In order to convert it into a JavaScript object, you must assess its validity first. If you have confidence in the source or are able to verify the information, you can achieve this by following these steps:

let script = document.createElement('script');
script.type='text/javascript';
script.innerHTML = 'const result = {'+ text + '}';
document.getElementsByTagName('head')[0].appendChild(script);

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

Is there a way to showcase an epub format book using only HTML5, CSS, and jQuery?

Can ePub format books be displayed in a web browser using only HTML5, CSS, and jQuery? I would appreciate any suggestions on how to accomplish this. Additionally, it needs to be responsive so that it can work on iPad. While I am aware of this requirement, ...

The handler provided to Boost::asio::async_read_until is never triggered

I am attempting to establish a connection between two computers on a local network. One is using a slightly modified version of the Boost Asio C++ TCP asynchronous server sample, while the other is running NodeJS. tcp_client.js : var net = require(' ...

Display an array depending on the value in Angular 2 when clicked

In my current Angular 2 project, I am dealing with a .json file structured like this: { "PropertyName": "Occupation", "DefaultPromptText": "occupation text", "ValuePromptText": { "WebDeveloper": "for web developer", "Administra ...

Issue with HighCharts Series Data Points Not Being Added

I am currently facing a major challenge in dynamically changing data for highcharts based on date. To provide context for my project, it involves logging system data with timestamps. I have implemented a date and time picker to specify the start and end da ...

Exploring the React Hook lifecycle methods of componentWillReceiveProps and componentDidUpdate

I am facing two main challenges: Despite the React guideline discouraging the use of derived state, there are still certain edge cases where it is necessary. In the context of a functional component with React Hook, what would be the equivalent implemen ...

Problem with Material-UI Drawer

Is there a way to make this drawer stay fixed on the page like a sticker and remain active without moving when scrolling? I've tried using docked={false}, but it makes the whole page inactive except for the drawer. Any suggestions on how to solve this ...

An interesting result from using fs.appendFile: the mysterious [object Object]

When utilizing console.log, the output of req.query (request.query) appears correct as { name: 'sean', comments: 'Hey' }. However, the issue arises when attempting to write this data to a file using fs.appendFile, as it ends up being wr ...

Managing unanticipated errors in Express while utilizing async/await mechanics

Consider this TypeScript code snippet: app.get('/test_feature', function (req: Request, res: Response) { throw new Error("This is the bug"); }); app.use(logErrors); function logErrors (err: Error, req: Request, res: Response, next: NextFun ...

Utilizing Vue.js components and properties to invoke a function

Trying to create a shopping cart button that keeps track of how many times it's clicked, but encountering an issue where the function called by the button doesn't receive the correct parameter. I attempted using {{id}} and :onClick="addThisToCar ...

Substituting text in a document by utilizing two separate arrays: one holding the original text to be found and another storing the corresponding text for

I am facing a challenge with replacing specific text strings in a file. I have two arrays - one containing the strings that need to be located and replaced, and the other containing the replacement strings. fs.readFile("./fileName.L5X", "utf8", function( ...

Can you provide some insight into why the init() method is throwing an error?

My project utilizes DynamoDB access through https://www.npmjs.com/package/react-native-dynamodb. I followed the code provided on the website for implementation. The issue I'm facing is that when hovering over my .init() method in WebStorm IDE, it sho ...

You are able to use a null type as an index in angular.ts(2538) error message occurred

onClick() { let obj = { fName: "ali", LName: "sarabi", age: "19", } let fieldName = prompt("field"); alert(obj[fieldName]); } I encountered an issue with the code above where alert(obj[fieldName] ...

Show a table when a button is clicked using Javascript

Undertaking a project called: Tennis Club Management involving javascript, HTML, CSS, and bootstrap. The project includes a Login Page (index.html) and a Manage Players Page (managePlayers.html). Within the managePlayers.html, there are two buttons - Add P ...

Which script, strophe.js or openfire, is responsible for closing the connection upon page refresh?

Currently, I am developing an application using Symfony2 that includes a chat feature. One aspect of this app involves utilizing session management for the chat functionality. 1) Upon logging in, I trigger an event listener to capture the user's cred ...

What is the best way to completely clear $rootScope when a user signs out of my application?

In my development work, I frequently find myself using $rootScope and $scope within controllers and services. Despite searching through numerous Stack Overflow answers for a solution to clear all $scope and $rootScope values, such as setting $rootScope t ...

Issue with autoplay slideshow functionality not activating when opened in a new tab

The owl.carousel.js plugin is used for creating a jQuery slideshow. Initially, the slideshow works correctly, but I noticed that the autoplay feature stops working when I open a new tab in Firefox or Chrome. Demo : Demo : $(document).ready(function () ...

Is it possible to send an entire HTML table to the server and then update the database table with it?

Recently, I encountered an issue that has me stumped. Suppose I have a database table A with multiple columns and the server (PHP script) renders this data into an HTML table for the web client. Now, the challenge lies in allowing users to add/delete rows ...

A guide on incorporating multiple nested loops within a single table using Vue.js

Is it possible to loop through a multi-nested object collection while still displaying it in the same table? <table v-for="d in transaction.documents"> <tbody> <tr> <th>Document ID:</th> &l ...

Can you explain the distinction between String[] and [String] in TypeScript?

Can you explain the distinction between String[] and [String] in typescript? Which option would be more advantageous to use? ...

Issue with routing in a bundled Angular 2 project using webpack

Having a simple Angular application with two components (AppComponent and tester) webpacked into a single app.bundle.js file, I encountered an issue with routing after bundling. Despite trying various online solutions, the routing feature still does not wo ...