0

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"

11
  • That first object isn't valid. Commented Jun 19, 2019 at 8:12
  • Why not JSON.stringify(obj) and then obj.id? Commented Jun 19, 2019 at 8:12
  • It's a string @JackBashford Commented Jun 19, 2019 at 8:12
  • Why not JSON.parse? Commented Jun 19, 2019 at 8:14
  • 1
    Where do you get this data from, why is it not proper JSON to begin with? Commented Jun 19, 2019 at 8:16

2 Answers 2

2

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);

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

2 Comments

No problem, but if you can change the API or the result of the API without front end code, I would still advise you to prefer that.
@Subramanian btw I have added a second answer, where you don't have to do your regex stuff before. You can just use your sCountry string with this.
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.