-1

I have got a problematic data from the server as string:

"{word_list: [{word: Small, phones: [{phone: s, quality: 56.33, extent: [77, 84]}, {phone: m, quality: 98.45, extent: [84, 89]}, {phone: ao, quality: 98.45, extent: [89, 102]}, {phone: l, quality: 98.28, extent: [102, 125]}]}]}"

I cannot perform JSON.parse on this data, as there are missing quotation marks on its strings(on the values but i would like to add the quotation marks on the keys as well)

Is there any regex that i could use to cover all of the strings in my data(but only the strings, not the arrays and numbers) so that i could perform the JSON.parse action easily?

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
user1322801
  • 839
  • 1
  • 12
  • 27
  • 5
    The server is sending you broken data. Fix it on the server-side, not the client-side. You could write your own parser, but that would be a *very* X/Y solution – CertainPerformance Oct 08 '19 at 09:33
  • Note that this is NOT "relaxed" JSON either. What is called "relaxed" JSON is compatible with JavaScript. JSON requires to quote keys and JS does not. Both however require to quote string *values*. – Nux Oct 14 '19 at 09:06

2 Answers2

-1

The problem is that it is not a JSON string. JSON is a standard of formatting objects in JavaScript-like fashion. And the data you've got is not even JS compatible.

Ask server-side developers to use a library to stringify objects on their side. There are plenty of libraries for multiple languages.

For example Jackson in Java: Converting Java objects to JSON with Jackson

And json_encode in PHP: https://devdocs.io/php/function.json-encode.

Nux
  • 9,276
  • 5
  • 59
  • 72
-1

As already mentioned the clean way is to fix it on the server side. If you have no access on the server side or whatever your reason may be, here are two ways to fix it on the client side:

  1. ONLY USABLE IF YOUR STRINGS DONT START OR END WITH NUMBERS: write a converter that fills in the quotation marks at the right places. You have to scan through the string and fill in quotation marks between those combinations(c!=[0-9]): '{c' 'c:' 'c,' 'c}' '[c' 'c]' ' c'

  2. ELSE: You have to check whole words. So you can split your String with all your brackets and commas and check for every word if it fits the number pattern. If it is -> You do nothing. Else -> add the quotation marks