For testing purposes, I wish to use Ajax to request some JSON from the server. From the Ajax client's perspective, the JSON should look like:
json=[
{"source":"pa","jsonstring": '{"a":1,"b":2,"c":3}'},
{"source":"pa","jsonstring": '{"a":1,"b":2,"c":3}'},
{"source":"pa","jsonstring": '{"a":1,"b":2,"c":3}'}
];
Note that jsonstring is not JSON, but a string, and $.getJSON() should not parse it into an object.
My attempt is below, however, I get error Parse error: syntax error, unexpected ',' in /var/www/test/src/classes/Ajax.php on line 13.
How should this be performed?
$content=file_get_contents('../buffer.json',true); //Line 13
$buffer=$content?json_decode($content):[];
$json=json_encode(['a'=>1,'b'=>2,'c'=>3]);
$buffer[]=[
'source'=>'pa',
'jsonstring'=>'"'.$json.'"'
];
$buffer=json_encode($buffer);
file_put_contents('../buffer.json',$buffer);
header('Content-Type: application/json');
echo($buffer);
buffer.json output is shown below:
[{"source":"pa","jsonstring":"\"{\"a\":1,\"b\":2,\"c\":3}\""},{"source":"pa","jsonstring":"\"{\"a\":1,\"b\":2,\"c\":3}\""}]
Have you tried removing the extra quotes from 'jsonstring'=>'"'.$json.'"'? If you json_encode it (which it looks like you do), then it is already a string. I think it should be 'jsonstring' => $json.
Related
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.
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".
I understand this question has been asked many times but I am still not able to get the error. I am trying to parse text coming from server.
"MARUTI"
"MAHINDRA AND MAHINDRA"
"FIAT"
Every texts parsed except "MAHINDRA AND MAHINDRA". I do not understand where the problem is. here is my code.
var myObject = JSON.parse(httpxml.responseText);
Error in Console
Uncaught SyntaxError: Unexpected token D
Please help.
Thats not a JSON String. You should inform about JSON
http://en.wikipedia.org/wiki/JSON
Return a JSON string from your server. With PHP you can use json_encode to encode an array to a json string.
I have an array via json_encode of PHP serialize:
json_encode(array('pattern' => '^(?:/?site/(?[\w\-]+))?(?:/?intl/(?[a-z]{2}(?:\-[a-z]{2})?)/?)?(/?(?.*))'));
// output json: {"pattern":"^(?:\/?site\/(?[\\w\\-]+))?(?:\/?intl\/(?[a-z]{2}(?:\\-[a-z]{2})?)\/?)?(\/?(?.*))"}
I tried to decode in Javascript:
JSON.parse('{"pattern":"^(?:\/?site\/(?[\\w\\-]+))?(?:\/?intl\/(?[a-z]{2}(?:\\-[a-z]{2})?)\/?)?(\/?(?.*))"}');
Then I don't understand why do I get an error "Uncaught SyntaxError: Unexpected token w" ??
Is PHP and Javascript JSON parser difference?
The problem is because you're using JSON.parse() and enclosing your JSON string in single quotes.
So your escaped regex string gets unescaped in the interpretation of the outer string-literal (single-quoted), and then gets mixed up in the interpretation of the value of the string pattern (double-quoted), ultimately causing JavaScript to choke trying to decipher "\w".
The following example, mimicking PHP rendering the JSON verbatim to a declaration, works fine in a JS console:
var json = {"pattern":"^(?:\/?site\/(?[\\w\\-]+))?(?:\/?intl\/(?[a-z]{2}(?:\\-[a-z]{2})?)\/?)?(\/?(?.*))"}
If you want to use JSON.parse, you have to first double-escape your JSON string in PHP
$json = json_encode(array('pattern' => '^(?:/?site/(?[\w\-]+))?(?:/?intl/(?[a-z]{2}(?:\-[a-z]{2})?)/?)?(/?(?.*))'));
$json = str_replace('\', '\\', $json);
// output json: {"pattern":"^(?:\\/?site\\/(?[\\\\w\\\\-]+))?(?:\\/?intl\\/(?[a-z]{2}(?:\\\\-[a-z]{2})?)\\/?)?(\\/?(?.*))"}
Then, in JS:
var json = JSON.parse('{"pattern":"^(?:\\/?site\\/(?[\\\\w\\\\-]+))?(?:\\/?intl\\/(?[a-z]{2}(?:\\\\-[a-z]{2})?)\\/?)?(\\/?(?.*))"}')
i tried using jquery ajax call, everything works fine until i tried to escape the json string using addslashes on the the server side i get the follow error : unexpected token illegal. here is my json string i cant find any problems in it
[{\"shortlist\":{\"id\":\"46\",\"application_id\":\"3\",\"created\":\"2012-04-
22\",\"modified\":\"2012-04-22\"},\"application\":
{\"id\":\"3\",\"admissionsession_id\":\"0\",\"school_id\":\"\",\"surname\":\"oni\",\"
other_names\":\"oluwafemi timothy Toluwalope\",\"date_of_birth\":\"0000-00-
00\",\"created\":\"2012-04-15\",\"modified\":\"2012-04-15\"}}]
if i remove the addslahes from the php json string it works fine. am scared of leaving my string unescaped tho.
add your data structure in an array:
$data = array('shortlist' => array('id' => 46, ....
then use:
$json = json_encode($data);
echo $json;