Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

json_encode adds double quotes when parsed

I am creating a JSON object in PHP like this:

echo json_encode(array("results" => array(array("user" => $member['user']),array("company" => $member['company']))));

In the JavaScript I get something like:

"{"results":[{"user":"David"},{"company":"something"}]}"

Then I try to validate this JSON and it is not valid, but when I remove double quotes at the beginning and at the end then it is validate JSON.

What am I doing wrong? This is how it should be:

{"results":[{"user":"David"},{"company":"something"}]}

EDIT:

part of my AJAX call:

success: function(response) 
        {
            for(var i=0;i<response.results.length;i++)
            {
              sessionStorage.setItem('user',response.results[i].user);
              sessionStorage.setItem('company',response.results[i].company);
            }
        }
like image 255
user123_456 Avatar asked Mar 28 '26 16:03

user123_456


1 Answers

You appear to be double-encoding it. Either that, or you're encoding it and then dumping it inside quotes.

To be clear, you should have something like this:

var myJSobject = <?php echo json_encode(...); ?>;

Then it's good to go, nothing else needed.

like image 116
Niet the Dark Absol Avatar answered Mar 30 '26 05:03

Niet the Dark Absol



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!