1

I have a string which is badly formated for JSON.parse.
It looks like this:
user_data = "{'key1':'val','key2':"bad_val with 'quoted' text"}"

I want to convert this somehow and parse with JSON.parse(). If it weren't for this bad_val simple replace(/'/g, '"') would help, but with this I'm stuck. What is the correct way of converting this?

Paweł
  • 81
  • 9
  • That's not a valid string declaration. Do you mean it's represented like `user_data = \`"{'key1':'val','key2':"bad_val with 'quoted' text"}"\``? – CertainPerformance Apr 25 '18 at 07:45
  • @CertainPerformance: How is your example different? I just character compared the two and can't find a difference. – Flater Apr 25 '18 at 07:47
  • Perhaps you want `user_data.key2.replace(/'/g, '\"')`. – deEr. Apr 25 '18 at 07:49
  • 1
    How is this JSON-like string generated/retreived? The best solution would be to correct the source of this string.. it shouldn't produce this format – Kaddath Apr 25 '18 at 07:50
  • @Flater His code cannot be declared as a Javascript string; mine can. Need to know what your actual string is – CertainPerformance Apr 25 '18 at 07:50
  • 1
    @Flater the difference is the `\`` characters, which allow to declare a string too in JS, so that there is no escaping problem with using `"` or `'` inside the string – Kaddath Apr 25 '18 at 07:54
  • 1
    You should not "fix" the string, but fix the source of it. – str Apr 25 '18 at 07:58

2 Answers2

0

You can use JSON.stringify() for converting it into JSON. For example:

var user_data = "{'key1':'val','key2':"bad_val with 'quoted' text"}";
var jsonObj = JSON.stringify(user_data);

It will return valid JSON format.

Pang
  • 9,564
  • 146
  • 81
  • 122
  • `JSON.stringify` an object to json string, if you pass `jsonObj` in `JSON.parse` you will only get a string and not an object – ekans Apr 25 '18 at 07:57
0

I assume the user_data is a bad formatted JSON which cannot be parsed with JSON.parse. If it's not possible to correct that string, then as a simple work around, you may try eval

let convertedUserData;
eval('convertedUserData = ' + user_data);

Though, this means executing script within that user_data string, therefore be aware of security issue. Again, not recommended at all

soyelmnd
  • 55
  • 7