0

I have to wrap some JSON in a response entity in order to pass it. The JSON looks like this:

{"headers":{"Content-Type":["application/json; charset=utf-8"]},"body":"\"[{\\\"name\\\":\\\"BFF\\\",\\\"id\\\":\\\"10713436\\\"}...

If I call $.parseJSON(thatthing.body), I get:

[{"name":"BFF","id":"10713436"},...

which looks good -- like a list of maps, which is what I expect. But If I call $.parseJSON(thatthing.body)[0], I just get the character '[' -- the literal first character of that text.

How do I instead treat this object like the list of maps that it is?

7
  • Can you post a demo to reproduce the issue? Commented Mar 8, 2014 at 1:02
  • @elclanrs Gladly. Can you show me how I can do that, noting that I barely understand the basics of html and javascript? Commented Mar 8, 2014 at 1:03
  • Try jsbin, jsfiddle, codepen, there are a bunch of options. Commented Mar 8, 2014 at 1:09
  • 1
    thatthing.body is a string that contains a string containing JSON. You have to parse twice. Better: Fix the code that generates this mess. Commented Mar 8, 2014 at 1:15
  • 1
    "\"[{\\\": It's a string (first "), which contains another string (\") which contains JSON ([{\\\"). Also, since you said that $.parseJSON(thatthing.body)[0] returns [, it means that $.parseJSON(thatthing.body) returns a string. Commented Mar 8, 2014 at 1:34

1 Answer 1

2

Whats happening is $.parseJSON is giving you a string, just parse it back into an object.

var Jstring = $.parseJSON(thatthing.body);
var Jobject = JSON.parse(Jstring); //<-- parse the sting back into json
Sign up to request clarification or add additional context in comments.

1 Comment

To be clear: $.parseJSON parses JSON and returns whatever the JSON decodes to. In this case it's a string. There is also no reason to use $.parseJSON and JSON.parse. Just use one of them.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.