April 22, 2012

What is wrong with these PHP scripts in reading JSON?

Question by Newbie

This is the code that I wrote:

$result = $textProc->sentiment($text);
$json_a = json_decode($result, true);
echo $json_a[label];

where $result stores the JSON data.

However, it returns me error:

Warning: json_decode() expects parameter 1 to be string, object given in C:xampp
htdocsaisentiment.php on line 9

Notice: Use of undefined constant label - assumed 'label' in C:xampphtdocs
aisentiment.php on line 11

Solution:
This is the output of var_dump($result):

object(stdClass)#2 (2) { ["value"]=> float(0.63882080795918) ["sent"]=> int(1) } 

Sorry, I should have checked this first.

Answer by Starx

Notice: Use of undefined constant label – assumed ‘label’ in
C:xampphtdocs aisentiment.php on line 11

On echo $json_a[label]; label refers to a constant which is not present.

To refer to an element in a associative array, you have do it as following.

echo $json_a['label'];

Warning: json_decode() expects parameter 1 to be string, object given
in C:xampp htdocsaisentiment.php on line 9

Next, on $result = $textProc->sentiment($text);, The function is not returning a string. Do a var_dump($result) to ensure, it is returning json string format.

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!