0

I intend to generate JSON that's like this:

{ "stores": [{"Name":"abc","Phone","1234567"},{"Name":"def","Phone","1111111"}], "numResults": 2 }

My php code is like this:

       while($row = mysql_fetch_assoc($result)){
            $store[] = $row;
            $k++;
       }
       $obj['stores'] = json_encode($store);           
       $obj['numResult'] = $numResult;           
       echo stripslashes(json_encode($obj));

However the result seems to have an extra pair of double quotes around the square brackets:

{ "stores": "[{"Name":"abc","Phone","1234567"},{"Name":"def","Phone","1111111"}]", "numResults": 2 }

How can I remove them? (Or is what's actually showing suppose to be the correct JSON formatting?)

Thanks!

1
  • You remove them by not adding them ;) Commented Nov 26, 2011 at 20:32

3 Answers 3

3

Only convert to JSON one time, once you have the complete object the way you want it:

       while($row = mysql_fetch_assoc($result)){
            $store[] = $row;
            $k++;
       }
       $obj['stores'] = $store; // <---------Note change           
       $obj['numResult'] = $numResult;           
       $myJSONstring = json_encode($obj);
Sign up to request clarification or add additional context in comments.

Comments

1

You wont need to json_encode twice. Create your $obj variable and json_encode that once it is completely created.

Comments

1

Simple way would be

$my_string = json_encode($my_json,JSON_FORCE_OBJECT);

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.