Subramanian
Subramanian

Reputation: 373

String to JSON convert

I am having String like this

{Name: India, Path: test.png, Id: 1, Uri: /api/1}

Through Javascript I tried to parse this value like this

 var sCountry = document.getElementById("countries").value; // this will give value as {Name: India, Path: test.png, Id: 1, Uri: /api/1}

  var fixedJSON = sCountry 

          // Replace ":" with "@colon@" if it's between double-quotes
                  .replace(/:\s*"([^"]*)"/g, function(match, p1) {
                    return ': "' + p1.replace(/:/g, '@colon@') + '"';
                  })

                  // Replace ":" with "@colon@" if it's between single-quotes
                  .replace(/:\s*'([^']*)'/g, function(match, p1) {
                    return ': "' + p1.replace(/:/g, '@colon@') + '"';
                  })

                  // Add double-quotes around any tokens before the remaining ":"
                  .replace(/(['"])?([a-z0-9A-Z_]+)(['"])?\s*:/g, '"$2": ')

                  // Turn "@colon@" back into ":"
                  .replace(/@colon@/g, ':')
  ;

  console.log('Before: ' + sCountry);
  console.log('After: ' + fixedJSON);//Output comes like this {"Name":  India, "Path":  test.png, "Id":  1, "Uri":  /api/1}

  var obj = JSON.parse(fixedJSON);

It gives error like this

   unexpected token e in json at position 10 at json.parse 

I guess the output should be like this

  {"Name":  "India" , "Path":  "test.png", "Id":  1, "Uri":  "/api/1"}

Can anyone help me to solve this String to JSON conversion. so that I can parse and get the value of "Id"

Upvotes: 0

Views: 106

Answers (2)

MauriceNino
MauriceNino

Reputation: 6747

Try it with split and join:

I have listed every step needed, but you can probably make it much smaller.

let val = '{"Name":  India, "Path":  test.png, "Id":  1, "Uri":  /api/1}';

// Remove brackets from string (first and last char)
let valWithoutBrackets = val.substring(1, val.length-1);

// Make key value pair array in string format (delimited by : )
let keyValuePairStrings = valWithoutBrackets.split(",");

// Make two dimensional key value pair array
let keyValuePairs = keyValuePairStrings.map(k => k.split(":").map(kv => kv.trim()));

// Map all values to values with brackets, except Id
let keyValuePairsWithBrackets = keyValuePairs.map(k => {
  if(k[0] != '"Id"') {
    k[1] = `"${k[1]}"`;
  }
  return k;
});

// Make two dimensional key value pair array to key value string array
let resultKeyValuePairStrings = keyValuePairsWithBrackets.map(k => k.join(":"));

// Make key value string array to list of keyvalues and add brackets again
let resultString = `{${resultKeyValuePairStrings.join(",")}}`;

// Log the parsed JSON Id
let obj = JSON.parse(resultString);
console.log(obj);
console.log(obj.Id);

Also you can skip your regex stuff if you add it directly to my code like this:

let val = '{Name: India, Path: test.png, Id: 1, Uri: /api/1}';

// Remove brackets from string (first and last char)
let valWithoutBrackets = val.substring(1, val.length-1);

// Make key value pair array in string format (delimited by : )
let keyValuePairStrings = valWithoutBrackets.split(",");

// Make two dimensional key value pair array
let keyValuePairs = keyValuePairStrings.map(k => k.split(":").map(kv => kv.trim()));

// Map all values to values with brackets, except Id
let keyValuePairsWithBrackets = keyValuePairs.map(k => {
  if(k[0] != 'Id') {
    k[1] = `"${k[1]}"`;
  }
  k[0] = `"${k[0]}"`;  // <-- Also put the key under quotations
  return k;
});

// Make two dimensional key value pair array to key value string array
let resultKeyValuePairStrings = keyValuePairsWithBrackets.map(k => k.join(":"));

// Make key value string array to list of keyvalues and add brackets again
let resultString = `{${resultKeyValuePairStrings.join(",")}}`;

// Log the parsed JSON Id
let obj = JSON.parse(resultString);
console.log(obj);
console.log(obj.Id);

Upvotes: 2

www.admiraalit.nl
www.admiraalit.nl

Reputation: 6089

With converting to JSON, you can easily get the items you want using split :

var result = sCountry.split(/ *, */);
var path = result[1].split(/ *: */)[1];
var id = result[2].split(/ *: */)[1];

Please add some error checking in case you get a string of an unexpected format.

Upvotes: 1

Related Questions