2

In PHP, I have a JSON object like so (even here not sure if its correctly formatted and if I'm passing it correctly):

$someJSONObject = '{token:"randomtoken",signature:"signature"};

and encode it before passing the response:

$response['code'] = 1;
$response['status'] = $api_response_code[ $response['code'] ]['HTTP Response'];
$response['data'] = $someJSONObject;

my_response($_GET['format'], $response);  //json_encode($response)

then in my JS I receive it in string format like this:

{ code:1,
  status:200,
  data: '"{token:\\"randomtoken\\", signature:\\"signature\\"}"' }

I parse it into an object:

phpObj = JSON.parse(body);

so I can access 'data':

dataObj = phpObj.data;

which gives me the result as a string:

{token:\"randomtoken\", signature:\"signature\"}  //console.log(dataObj)

it's here where I lose my way and not able to access 'token' getting an undefined:

console.log('token: ' + dataObj.token)    //token:undefined  

I realize I'm trying to dot into a string, so I must be doing something wrong at this last step. However, even if I try to use JSON.parse or JSON.stringify it still doesn't seem to help and gives me an 'undefined'.

dataObj = JSON.parse(phpObj.data);
console.log(typeof(dataObj);            //string
console.log(dataObj);                   //"\"{token:\\\"randomtoken\\\", signature:\\\"signature\\\"}\""
console.log(dataObj.token);             //token: undefined 

or

 dataObj = JSON.stringify(phpObj.data);
 console.log(typeof(dataObj));          //string
 console.log(dataObj);                  //"\"{token:\\\"randomtoken\\\", signature:\\\"signature\\\"}\""
 console.log(dataObj.token);            //token: undefined

Any help/feedback would be appreciated.

3 Answers 3

4

You should NOT be embedding json-in-json. It's rather pointless. Deal with a purely NATIVE data structure, e.g.

$response = array(
   'code' => 1,
   'status' => xxx,
   'data' => array
         'token' => 'randomtoken',
         etc...
   )
);

And then encode that:

echo json_encode($response);

The JS side will decode that back into a native JS structure, and then you have, simply:

alert(response.data.token);

with no extra decoding steps, no worries about escaping quotes, etc...

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

3 Comments

Time and time again people keep trying to encode their own JSON when PHP has a function for it. I would like to know if you have a theory as to why this is the case all too often? Am I missing something, are there cases where json_encode() isn't good enough and I am simply the noob?
Thank you, Marc B. I changed:
Thank you, Marc B. I changed how I constructed the JSON object on the PHP to how you suggested and only initially parse the response with no extra decoding step. MonkeyZeus - I don't use PHP and it was obviously an error on my part with regard to how I handled JSON.
1

First, this is not valid JSON:

 $someJSONObject = '{token:"randomtoken",signature:"signature"};

You need to enclose the keys in ". Better still, let PHP do it:

$someJSONObject = json_encode(array(
    'token' => 'randomtoken',
    'signature' = 'signature'
));

The really odd thing you're doing, however, is attempting to include a string of JSON in another string of JSON. This is, to put it mildly, confusing.

Instead, pass the data to my_response as an array, and let json_encode encode the whole lot.

$someJSONObject = array(
    'token' => 'randomtoken',
    'signature' = 'signature'
);
my_response($_GET['format'], $response);

In your Javascript, you should then be able to do phpObj.data.token.

2 Comments

Thanks for the feedback, lonesomeday. I actually meant to have the keys enclosed in quotes for the code I shared, but in my flustered/rush state shared the wrong code...I credit Marc B since his came in first, but appreciate your response....I tried manipulating the JSON object in the browser console and it seem to work the other way. Anyhow, thanks.
@DevPer No problem at all.
0

I have a code similar but, my json looks like this

{ "token" [ "token": randomtoken, "signature": signature] }

then I manipulate like this:

var datos = JSON.parse(JSON);      
    for(var something in datos){
      var objeto = datos[something];
      alert('token: ' + objeto.token);
    }

sorry my bad english

1 Comment

Is this a question or an answer?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.