1

Is it possible using JavaScript to convert a string like this:

"Product : Bike , 2005 : $12000,2006 : $13000,2007 : $14000,2008 : $15000"

to a JSON object like this:

{
    "Product":"Bike",
    "2005" : $12000,
    "2006" : $13000,
    "2007" : $14000,
    "2008" : $15000
}
5
  • 4
    Yes, it is possible. Commented Jul 22, 2017 at 18:34
  • 2
    The JSON you expect is no valid JSON Commented Jul 22, 2017 at 18:35
  • can u suggest any idea? Commented Jul 22, 2017 at 18:35
  • 1
    It's probably best to use a regular expression if your string has always the same structure. Commented Jul 22, 2017 at 18:40
  • What do you want exactly? Parse your first expression into a javascript object or convert it into a JSON formatted string? Commented Jul 22, 2017 at 18:40

4 Answers 4

1

Assuming structure of your string will be the same, split with , will give you array of key/value pairs, then split each pair with : you will get key and value.

var str = "Product : Bike , 2005 : $12000,2006 : $13000,2007 : $14000,2008 : $15000"
var obj={};
str.split(",").forEach(function(item){
    var keyVal = item.split(":")
    obj[keyVal[0].trim()] = keyVal[1].trim()
})
console.log(obj)

Sign up to request clarification or add additional context in comments.

Comments

1

You can split the string on , and on :. Make sure to also trim the resulting strings, because there is otherwise whitespace around the terms.

var string = "Product : Bike , 2005 : $12000,2006 : $13000,2007 : $14000,2008 : $15000";
var result = {};
var duplets = string.split(',');

for (var i = 0; i < duplets.length; i++) {
  var duplet = duplets[i];
  var values = duplet.split(':');
  result[values[0].trim()] = values[1].trim();
}

console.log(result);


You could also use a regular expression:

var string = "Product : Bike , 2005 : $12000,2006 : $13000,2007 : $14000,2008 : $15000";
var regex = /(?:^|,)([^,:]+):([^,]+)(?=$|,)/g;

var result = {};
while(match = regex.exec(string)) {
  result[match[1].trim()] = match[2].trim();
}
console.log(result);

Here are some information about the regex:

  • (?:^|,) matches the beginning of the string (^) or a ,
  • ([^,:]+): matches every character except , and : multiple times up to the next : and forms the first selection group
  • ([^,]+)(?=$|,) matches every character except , multiple times up to the end of the string $ or the next ,. It forms the second matching group.

Comments

1

Using replace() with RegExp

Broken down, the regular expression matches like this:

  1. \s* any amount of whitespace (including none)
  2. followed by (\:|,){1} a capture group of either 1 colon or 1 comma
  3. followed by \s* any amount of whitespace (including none)
  4. then the flag g enforces matching of all occurrences until the end of the string.

And the matches are replaced by the captured value $1 surrounded by quotes ".

This results in all leading and trailing whitespace around the property names and values being trimmed, and the property names and values being properly quoted.
We then only need to add quotes and braces at either end of the string to make it a valid JSON string ready to parse() into an object.

const str = "Product : Bike , 2005 : $12000,2006 : $13000,2007 : $14000,2008 : $15000",

      json_str = '{"' + str.replace( /\s*(\:|,){1}\s*/g, '"$1"' ) + '"}',

      js_object = JSON.parse( json_str );

console.log( json_str ); // transportable
console.log( js_object ); // useable

Comments

0
JSONParser parser = new JSONParser();
JSONObject json = (JSONObject) parser.parse(stringToParse);

3 Comments

this is which language? :O
The question clearly stated JavaScript, not TypeScript.
@ErickPetrucelli...nor Java. I think it uses JSON.org's library

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.