parsing JSON in php using angularJS object - php

I am trying to pass JSON object from angular to php like this :
<?php
$placeBean = "{{masterCtrl.getLastplace();}}";
//VAR DUMP IS -> string(30) "{"id":1841,"name":"Milano","areaCode":"MI","latitude":0,"longitude":0}"
$json = '{"id":1841,"name":"Milano","areaCode":"MI","latitude":0,"longitude":0}';
//VAR DUMP IS -> string(70) "{"id":1841,"name":"Milano","areaCode":"MI","latitude":0,"longitude":0}"
?>
Then I need to parse the json in $placeBean, because it is not yet a json in php, so I use
<?php
$manage = json_decode($placeBean);
?>
And this is the problem... because it doesn't work, in fact the result is an empty value: instead, if I do the same thing with $json( instead of $placeBean), the code works perfectly.
I Think the issue is some
missing chars, which are placed in$json, and not in $placeBean.
Those are the echo of the variables
ECHO OF JSON ->{"id":1841,"name":"Milano","areaCode":"MI","latitude":0,"longitude":0}
ECHO OF placeBean ->
placeBean{"id":1841,"name":"Milano","areaCode":"MI","latitude":0,"longitude":0}
I Also tried to use json_last_error, which gave me this : - Syntax error, malformed

Well, the first one is not a valid JSON object, for this PHP refuses to parse it.
When you run it though AngularJS it will actually use its own mechanism and replaces the string with the data returned by the masterCtrl.getLastplace() call.

Related

PHP Json Values from Keys not being parsed from External API Call

I am trying to make an external API call to fetch JSON data and return it within my web app.
Here is what the data looks like from the API call:
JSON returned from URL:
{
"results":[
{
"name":"Company1",
"ProviderName": "ProviderName1",
"ProviderLogo": "/images/some_image1.jpg",
"GetURL": "/some_url_path",
"Costs": 10000.50
},{
"name":"Company2",
"ProviderName": "ProviderName2",
"ProviderLogo": "/images/some_image2.jpg",
"applyURL": "/some_url_path",
"Costs": 12000.50
}]
}
Since I am using PHP, I am using the following code:
$api_data = file_get_contents('MY URL');
// Had to use 'encoded_json()' since 'json_decode()' was initially returning NULL
$encoded_json = json_encode($api_data);
$decoded_json = json_decode($encoded_json);
// Now I want to get the specific values from the JSON result but nothing is being returned
// I tried using something like this but I'm not getting anything
foreach($decoded_json->results as $mydata)
{
echo 'Decoded Name: ' . $mydata->name . "\n";
}
Any help is greatly appreciated!
EDIT:
So this what was actually happening and I'm going to apologize to everyone in advance right now because I didn't include what was actually throwing the error off in the first place!
I used JSON Lint and put all of the API Json data that I was receiving and it showed me where the error was occurring.
Error:
"SomeCostUpper": $some_variable.rawUpperCost
I tested out my PHP code using valid JSON and was able to return the results without a problem.
Everyone, I'm really sorry for the confusion but thanks for your efforts!
$api_data = file_get_contents('MY URL');
You now have a string containing the data in that URL.
// Had to use 'encoded_json()' since 'json_decode()' was initially returning NULL
If json_decode returns NULL, then the string you had does not contain valid JSON.
$encoded_json = json_encode($api_data);
You now have a string representation of a string containing the data from the URL.
$decoded_json = json_decode($encoded_json);
And now you have reversed that, so you have your original string back.
foreach($decoded_json->results as $mydata)
It is a string. You can't do that.
You need to fix the data you are getting from MY URL.
Use a tool like JSON Lint, which will give you an error like:
Error: Parse error on line 7:
..."Costs": 10000.50, }, { "name": "Comp
----------------------^
Expecting 'STRING', got '}'
You have a rogue comma after the last entry in your object.
This is likely caused by generating JSON by mashing together strings or by writing it by hand. Avoid that. Use tools and libraries designed to generate JSON.
I don't know from which website you get that JSON data, but it isn't valid JSON, that is why json_decode() initially returned NULL. There are 2 commas (each costs value has one) that shouldn't be there.
You "fixed" that by using first json_encode() and then json_decode() on the JSON data returned from the API call. You might think that that fixed your problem but no, if you take a look at what is inside $decoded_json you will see that there isn't an object or an array which you can use.
That means that when you try to do
foreach($decoded_json->results as $mydata)
{
echo 'Decoded Name: ' . $mydata->name . "\n";
}
It fails because it cannot iterate over the 'string' inside $decoded_json.
If you had turned on error reporting you would have seen the following errors:
E_NOTICE : type 8 -- Trying to get property of non-object -- at line n
E_WARNING : type 2 -- Invalid argument supplied for foreach() -- at line n
the json is ok, you don't need to encode and then decode again...
just do:
$api_data = file_get_contents('MY URL');
$decoded_json = json_decode($api_data );
foreach($decoded_json->results as $mydata)
{
echo 'Decoded Name: ' . $mydata->name . "\n";
}
Your JSON data is not valid. Here is the valid JSON structure.
Remove the ',' from the last elemp "Costs": "10000.50" and use double quote for the value as "10000.50".

Get json string elements

I am using a astrology API which sends an json string as response to the query. But i have been trying for long to convert it into json and retrieve different items from the response string. Here is the example of the response:
{"ashtakoota":{"status":true,"received_points":26},"manglik":{"status":true,"male_percentage":13.25,"female_percentage":13.75},"rajju_dosha":{"status":false},"vedha_dosha":{"status":false},"conclusion":{"match_report":"Marriage between the prospective bride and groom is highly recommended. The couple would have a long-lasting relationship, which would be filled with happiness and affluence."}}
I am using php script so i tried the following code :
$json = json_decode($res1, true);
TRY 1 --> echo array_values($json[1]);
TRY 2 --> echo $json.ashtakoota.status;
TRY 3 --> echo $res1.ashtakoota.status;
But the output is always blank. I doubt that $json is empty or the json response is not perfectly json.
PHP uses string keys for its arrays, which is what json_decode(...) returns. As such, you need to access them as:
echo $json['ashtakoota']['status'];
Which should then output true for your example JSON input.
The true parameter on json_decode will cause it to return an array, not an object. Your syntax for objects is also incorrect, it's not a dot, but rather -> that you need.
$json = json_decode($res1);
echo $json->ashtakoota->status;

php json_decode error quoted object property name expected

I try to create a script that decoding a simple JSON string in PHP and I get the following error:
quoted object property name expected
The string I try to decode is the following :
{"values":[{"url":"http://www.google.com","matches":"http|www|google|com"},{"url":"http://www.yahoo.com","matches":"http|www|yahoo|com"}]}
and the code I use to decoded is the following:
json_decode( $json_string );
I also have try to validate my json string in some online json validators, and the string seems to be fine.
Can someone please help me ?
Do you think the problem exists because of the double quotes ?
Update #1
Definetelly was a debuging issue. I place my experience here just to help other devs may come accross the same issue in the feature:
The problem was that my variable that came with the json string was html encoded so instead of the following string :
{"values":[{"url":"http://www.google.com","matches":"http|www|google|com"},{"url":"http://www.yahoo.com","matches":"http|www|yahoo|com"}]}
my variable came with the following string inside :
{"values":[{"url":"http://www.google.com","matches":"http|www|google|com"},{"url":"http://www.yahoo.com","matches":"http|www|yahoo|com"}]}
The mistake by my side was that I used the print_r method instead of the var_dump . This had as a result to print out the &quot as " in my page .
The json string is valid, and it works. You can add true for the second parameter of json_decode, and you get back an array.
Try the following:
$json_string = '{"values":[{"url":"http://www.google.com","matches":"http|www|google|com"},{"url":"http://www.yahoo.com","matches":"http|www|yahoo|com"}]}';
var_dump(json_decode($json_string, true));
It works for me.

PHP base64_decode returning nothing

The site I am working on is using a .net Soap web service for getting data. The initial call returns XML that contains a base64 encoded string. I am able to isolate that string by using $lastResponse = $client->__getLastResponse(); When I use var_dump on the $last response variable I get some thing like
string(10139) "77u/PD94bWwgdmV...=="
When I use echo I get 77u/PD94bWwgdmV...== without the string(10139) to start. I have tried to place the $lastResponse variable into the base64_decode function but it returns nothing at all, not even NULL. I have also tried to split the string first to remove the 77u/ from the start and that does not work at all.
$lastResponse = $client->__getLastResponse();
$splitResponse = preg_split("#/#", $lastResponse);
echo base64_decode($lastResponse);
echo base64_decode($splitResponse[1]);
var_dump($splitResponse[1]);
var_dump(base64_decode($splitResponse[1]));
echo $lastResponse;
The code above returns this to the browser:
string(0) "" string(0) "" 77u/PD94bWwgdmVyc2lvbj0....
But when I copy/paste everything after the 77u/ into an only decoder I get the decoded xml that I am supposed to have returned to me. I am very confused as to what I am missing here any help will be greatly appreciated.

JSON from Javascript not decoding in PHP

I've been going bananas trying to get some data from Javascript on one page to post to a php file asynchronously. I'm not even attempting to do anything with the data, just a var_dump to spit back out from the ajax call. NULL over and over again.
I've checked the JSON with JSONLint and it validates just fine. I'm getting my JSON from JSON.stringify - Firebug tells me I'm getting the following:
{"items":[["sa1074","1060"],["sa1075","1061"]]}
I've tried php://input, as well as json_decode_nice from the PHP manual comments about the function, and I've tried using utf8_encode - is there something wrong with my JSON?
EDIT: Derpity dee probably should have planned this post a bit more haha. Here's my PHP (using a suggestion from PHP manual comments)
function json_decode_nice($json, $assoc = FALSE){
$json = str_replace(array("\n","\r"),"",$json);
$json = preg_replace('/([{,])(\s*)([^"]+?)\s*:/','$1"$3":',$json);
return json_decode($json,$assoc);
}
if (isset($_POST['build'])){
$kit = file_get_contents('php://input');
var_dump(json_decode_nice($kit));
}
And the JS used to create it:
var jsonKit = JSON.stringify(kit);
$.post("kits.php?", {"build" : jsonKit},
function(data) {
$("#kitItems").html(data);
});
Also: Our host is on PHP 5.2 - I found this out when I uploaded a perfectly good redbean class only to have it explode. Had to re-implement with legacy redbean. Our host is busted.
SOLVED: Thanks to all who commented. Didn't think to check $_POST to see what was coming in. Quotes were being escaped with slashes in the $_POST and json_decode was choking on it. Adding this line before decoding solved the problem. Also forgot to set true to return an associative array. Thanks!
$kit = str_replace('\\', '', $kit);
Without seeing code - I'm just guessing here ... are you using a true assoc variable in your json_decode()?
<?php json_decode($jsonString, true); ?>
That had me stumped on a decode for quite some time my first time trying to decode something,

Categories