Deciphering JSON string without quotation marks

What's the most straightforward way to parse an unquoted JSON string?
For instance, if I have something like this:

{property1:value1, property2:value2}

Using the following code will result in an error:

JSON.parse(badJSONString);

This is because a valid JSON should have keys and values enclosed in quotes: {"property1":"value1"}

Answer №1

If your data is consistent (and that might be a big if), you can apply a straightforward function to process the string. This method may prove inadequate when dealing with strings containing commas or colons in the values, such as '{property1:val:ue1 ,property2:val,ue2}', but these scenarios would likely pose challenges regardless without proper delimiters.

let bad = '{property1:value1,property2:value2}'
let obj = bad.slice(1, -1).split(/\s?,\s?/)
    .map(item => item.split(':'))
    .reduce((a, [key, val]) => Object.assign(a, {[key]: val}), {})

console.log(obj)

Answer №2

One potential solution is as follows:

var str = "{key1:value1,key2:value2}"; // string (unquoted JSON)

var cleanStr = str.trim().substring(1, str.length - 1); // remove curly braces

var keyValuePairs = cleanStr.split(',');              // create an array like ["key1:value1", "key2:value2"]
var result = {};
var pair;
for (var index = 0, length = keyValuePairs.length; index < length; index++) {
  pair = keyValuePairs[index].split(':');               // create an array like ["key1","value1"]
  result[pair[0].trim()] = pair[1].trim();   // assign value to key (remove whitespace from both ends)
}
console.log(result)

Check out the code on jsfiddle

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

The perplexing results received when using the npm outdated command

Could someone provide an explanation for the meaning behind this output? $ npm --version 3.10.8 $ npm -g outdated npm Package Current Wanted Latest Location npm 3.10.8 4.0.2 3.10.9 As stated in the documentation, the "Wanted" column should d ...

Create a toggle effect using attribute selectors in CSS and JavaScript

I am looking to switch the "fill: #000;" from the CSS property "svg [id^='_']". Usually, I would use a method like this, but it seems that I can't do so because "svg [id^='_']" is not an element, correct? pub.toggleClass = functi ...

Unfortunately, the input type number does not allow for the removal of decimal points

I need assistance with modifying the HTML code below. I want to remove the decimal point from the input field. Could anyone please provide instructions on how to accomplish this? <input type="number" min="0" step="1" ng-pattern="/^(0|[1-9][0-9]*)$/" ...

Creating a line break in a Vue.js confirmation dialog is a helpful feature that can be achieved with a

Is there a way to add a new line after the confirmation dialog question and insert a note below it? this.$dialog.confirm("Create Group","Would you like to create group "+ this.groupName +"?<br/>(NOTE: Selected project or empl ...

Troubleshooting the issue of JavaScript not executing on elements with a specific CSS class

I am attempting to execute a JavaScript function on each element of an ASP.NET page that is assigned a specific CSS Class. Despite my limited knowledge of JavaScript, I am unable to determine why the code is not functioning properly. The CSS Class is being ...

Implementing the 'bootstrap tour' feature in a Ruby on Rails application

I have integrated bootstrap-tour.min.css and bootstrap-tour.min.js into my project. <script type="text/javascript" src='bootstrap-tour.min.js'></script> <link rel="stylesheet" type="text/css" href="bootstrap-tour.min.css"> Her ...

"What is the best way to access the value of a useState variable in ReactJS on a global

Below is my reactJS code snippet - useEffect(()=>{ const getinterviewerDetails= async ()=>{ const data1 = await axios.get("http://localhost:8083/api/GetProduct") .then(response => { console.log("role is " ...

lowdb only modifies a single piece of information in the JSON file

When updating a JSON file with a lowdb request, only the date gets updated. Upon logging the information to be updated, this is the desired update: res.on("end", function () { let body = Buffer.concat(chunks); let final = JSON.parse ...

Tips for showing a success notification once a PHP script has been successfully completed on a form

Hey everyone, I need some help with a PHP script that I have connected to a single input form. I'm looking to create a success page for users after they submit their email, with a link back. This seems simple enough, but I'm still learning PHP. ...

`Optimizing Performance using jQuery Functions and AJAX`

As someone exploring ajax for the first time, I'm eager to learn how to write jQuery code that ensures my simple functions like slideshows and overlays still work smoothly when a page is loaded via ajax. Currently, I am implementing the following met ...

Leveraging a single jquery ajax request to handle various loops

I've been pondering if it's possible to have multiple loops, each with its own Ajax call. My goal is to create a golf scorecard where I can retrieve data for the scorecard and players in a single JSON/Ajax call... This is how I retrieve the scor ...

How can I fetch data from a PHP file using an Ajax request?

Recently, I delved into the realm of Ajax requests and devised this script: function ajax_post(){ // Initiating XMLHttpRequest object var xmlhttp = new XMLHttpRequest(); // Setting up necessary variables for sending to PHP file var url = " ...

Unexpected equals sign caused JSON conversion to fail

I'm attempting to create JSON for sending to a webservice. The desired final JSON should appear as follows: { "name": "Pravidlo", "partQualities": [ "A", "O", "N" ], "residualValueMax": 100, "residualValueMin": 0, "selectionSt ...

Retrieving data from a SimpleXMLElement in PHP

Showing the following information: [1]=> object(SimpleXMLElement)#6 (1) { ["@attributes"]=> array(14) { ["name"]=> string(5) "MySQL" ["acknowledged"]=> string(1) "1" ["comments"]=> string(1) "1" ["current_c ...

Changing id to a model in params in Rails 4

Whenever I attempt to add a new record in the DB, my code encounters an error: @user_request = UserRequest.new(user_request_params) I have a model that has a relationship with another model. The user picks the sub model from a dropdown menu, and the id i ...

Loading a Vue.js template dynamically post fetching data from Firebase storage

Currently, I am facing an issue with retrieving links for PDFs from my Firebase storage and binding them to specific lists. The problem arises because the template is loaded before the links are fetched, resulting in the href attribute of the list remainin ...

Tips for creating multiple entries in JSON format

I'm facing an issue where each time I try to save a new RSS record to a JSON file, it ends up overwriting the previous one. How can I store multiple RSS records in the same file without losing any data? private void saveJSONtoFile(String jsonString) ...

I am having issues with the external CSS and JS files not functioning properly in my project

I'm currently working on a project that has the following file structure: https://i.sstatic.net/ixd9M.png However, I am facing issues with loading my CSS and JS files... <link rel="stylesheet" href="./css/main.css"> <sc ...

"Step-by-step guide on deactivating SmartyStreets/LiveAddress with an onclick function

I've recently taken over a SquirrelCart shopping cart application that utilizes SmartyStreets/LiveAddress code, and I'm struggling to figure out how to disable the verification process when copying billing address fields to shipping address field ...

Can the order of event bubbling be altered in JavaScript?

I have three boxes in my HTML, each with its own click events. Currently, when I click on a child element, event bubbling occurs in the order of C->B->A. However, I am curious to see if it's possible to change the event bubbling order to C-> ...