1

I have a problem parsing a json string.

Here's the string (the problematic part of it):

{
    "type":"meaning",
    "terms":[
    {
       "type":"text",
       "text":"some value.",
       "language":"ru"
    },
    {
       "type":"url",
       "text":"\x3ca href\x3d\x22http://readmas.ru/arts/bodyart/znachenie-tatuirovok.-chast-i.html\x22\x3…ttp://readmas.ru/arts/bodyart/znachenie-tatuirovok.-chast-i.html\x3c/a\x3e",
       "language":"ru"
   }]
},

Note:
These function doesn't work for me:

  1. string replace.
  2. JSON.parse.
  3. $.parseJSON.
5
  • this is looking ok please tell us much more about problem Commented Jan 13, 2014 at 7:11
  • I'm actually developing a chrome extension and this string is returned to me by google dictionary. I can't change the way the request is beind made (because it is the only way to get an answer from google). Here's the request: Commented Jan 13, 2014 at 7:14
  • 2
    There are no workarounds, except maybe a search and replace on the string itself, as you have invalid JSON, and it can't be parsed. Commented Jan 13, 2014 at 7:14
  • var url = "google.com/dictionary/json?callback=_&q=" + word + "&sl=ru&tl=ru&restrict=pr%2Cde&client=te"; $.ajax({ type: "GET", url: url, dataType: "text", success: function (responseText) { var code = responseText.trim().substr(2, responseText.lastIndexOf("}") - 1); }, error: function (data) { } }); Commented Jan 13, 2014 at 7:15
  • string replace isn't working for me. is there any other way to replace the invalid characters before parsing an object? Commented Jan 13, 2014 at 7:16

1 Answer 1

4

Unlike JavaScript, the JSON notation only supports the two-byte \uNNNN escape sequences, not the \xNN sequences. Try this:

var cleaned = input.replace(/\\x([0-9a-f]{2})/g, '\\u00$1');
var output = $.parseJSON(cleaned);
console.log(output);

Demonstration

Also, in order to make this demonstration work, I had make a couple other modifications to your string, which I think are just a result of how you formatted the question here:

  • Completed the \xNN escape sequence that was broken when in the middle of the string (\x3…ttp).
  • Removed the comma at the end of the object literal.

In any case, it would probably be better if you could make your service (or whatever is giving you this file) provide you valid JSON instead this.

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

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.