I'm trying to extract a specific value from json content . Here it is link with the json code http://www.ebayclassifieds.com/m/AreaSearch?jsoncallback=json&lat=41.1131514&lng=-74.0437521 As you may see the the code displayed is
json({items:[{url:"http://fairfield.ebayclassifieds.com/",name:"Fairfield"},{url:"http://newyork.ebayclassifieds.com/",name:"New York City"}],error:null});
I need to extract the first url which in this case is "http://fairfield.ebayclassifieds.com/" and its name value which is "Fairfield" , I could do it with regex but I would prefer to use json_decode. Unfortunately when I try to decode it doesn't work
$json = getContent("http://www.ebayclassifieds.com/m/AreaSearch?jsoncallback=json&lat=41.1131514&lng=-74.0437521");
$test = json_decode($json, true);
As danp already said, the returned JSON is enclosed in a function call (specified by jsoncallback=json). You cannot get rid of this totally but, just using AreaSearch?jsoncallback=&lat=41.1131514&lng=-74.0437521 removes at least the json at the beginning of the string and you can get rid of the brackets by:
$json = trim(trim($json), "();");
with gives:
{items:[{url:"http://fairfield.ebayclassifieds.com/",name:"Fairfield"},{url:"http://newyork.ebayclassifieds.com/",name:"New York City"}],error:null}
Unfortunately, the JSON string is not valid. The keys (items, url, ...) have to be enclosed in quotes ". You can easily check that you get a syntax error with json_last_error() (error code 4, JSON_ERROR_SYNTAX).
Update:
According to this question: Invalid JSON parsing using PHP , you can make the JSON string valid with:
$json = preg_replace('/(\w+):/i', '"\1":', $json);
This encloses the keys in quotes.
If the string would be valid, then you could generate an array via:
$a = json_decode($json, true);
which would give you:
Array
(
[items] => Array
(
[0] => Array
(
[url] => http://fairfield.ebayclassifieds.com/
[name] => Fairfield
)
[1] => Array
(
[url] => http://newyork.ebayclassifieds.com/
[name] => New York City
)
)
[error] =>
)
So you could get the first URL and name via $a['items'][0]['url'] and $a['items'][0]['name'] resp.
But I repeat, the JSON you get as response is not valid and you cannot parse it with json_decode() in its original form.
Its not valid JSON. The keys should be wrapped inside quotes.
You can validate your json using the excellent JSON Lint site.
This is a valid version of the data returned:
{
"items": [
{
"url": "http://fairfield.ebayclassifieds.com/",
"name": "Fairfield"
},
{
"url": "http://newyork.ebayclassifieds.com/",
"name": "New York City"
}
],
"error": "null"
}
Related
I have a PHP array as follows:
Array
(
[Caller] => EFLwebsite
[CaseDetails] => Array
(
[Description] => This is a Site Readiness case.
[SAPCustomerCode] => 1001140090
[ProductNumber] => GWPDREVIV00000
[CustomerAssetSerialNumber] => 000000000418005207
[RequestedDate] => 2021/01/06
[RequestedTime] => 10:00:45
[BP] => CRM Test User
)
)
I need to convert the above array into json as follows:
{
"Caller":"EFLwebsite",
"CaseDetails":"{\"Description\":\"This is a Site Readiness case.\",\"SAPCustomerCode\":\"0100301500\",\"ProductNumber\":\"GWPDFCOND00000\",\"CustomerAssetSerialNumber\":\"000000000418005207\",\"RequestedDate\":\"2021\/01\/06\",\"RequestedTime\":\"23:54:12\",\"BP\":\"CRM Test User\"}"
}
I am using addslases() after json_encode but it returns as follows:
{
\"Caller\":\"EFLwebsite\",
\"CaseDetails\":{\"Description\":\"This is a Site Readiness case.\",\"SAPCustomerCode\":\"1001140090\",\"ProductNumber\":\"GWPDREVIV00000\",\"CustomerAssetSerialNumber\":\"000000000418005207\",\"RequestedDate\":\"2021\\/01\\/06\",\"RequestedTime\":\"10:00:45\",\"BP\":\"CRM Test User\"}
}
I need to add the slashes only to the second value which is CaseDetails
I also tried encoding the subarray separately and adding slashes as a string, but it is adding more slashes again.
I also have no idea why you would want to do this, but this should do the trick:
$array = [
"Caller" => "EFLwebsite",
"CaseDetails" => [
"Description" => "This is a Site Readiness case.",
"SAPCustomerCode" => "1001140090"
]
];
// first convert case details to json
$array["CaseDetails"] = json_encode($array["CaseDetails"]);
echo "<pre>";
print_r(json_encode($array)); // then convert everything to json
echo "</pre>";
This returns:
{"Caller":"EFLwebsite",
"CaseDetails":"{\"Description\":\"This is a Site Readiness case.\",\"SAPCustomerCode\":\"1001140090\"}"}
Using heredoc string with php. Docs
Heredoc text behaves just like a double-quoted string, without the double quotes. This means that quotes in a heredoc do not need to be escaped, but the escape codes listed above can still be used. Variables are expanded, but the same care must be taken when expressing complex variables inside a heredoc as with strings.
$case = addslases(json_encode($array['CaseDetails']));
$json = <<<EOT
{ "Caller": "{$array['Caller']}", "CaseDetails": {$case} }
EOT;
echo $json;
I have a python script which returns an object as string. I call this python script with php and then print out the result with var_dump(json_decode($result)) and get this (this it the right object I want so my python code works properly I guess):
string(467) "{"userData": {"geburtsdatum": "PMS_2018-01-01", "anrede": "PMS_Herr", "ID": "1", "nachname": "PMS_Nachname1", "Test": {"tel": "PMS_Tel1", "postalOptIn": 0, "postal": "S3_Postal1", "email": "PMS_EMail1"}, "vorname": "PMS_Vorname1" }} "
So as you can see its a string on php side.
But how can I convert it to an object now and the create a multidimensional array from it in php?
If you need more information pls ask Ill add it.
I tried:
json_decode($result, true);
json_decode($result);
$response = (array) $result;
all I get is an Array with 1 Index and the whole Object as Value in it.
The Object gets generated like this on python side:
for message in consumer:
if message.key == str.encode(sys.argv[1]):
returnValue = message.value #this here is an byte obj from external system
consumer.close()
print(returnValue.decode("latin-1"))
Edit 2 and Solution
After long search I found out that the service I'm using (3d Party) returns the result from the python script with json_encode(). I removed that and now this code works:
$array = json_decode($response, TRUE);
return var_dump($array);
Since it is a string you can decode it like this:
$string = '{"userData": {"geburtsdatum": "PMS_2018-01-01", "anrede": "PMS_Herr", "ID": "1", "nachname": "PMS_Nachname1", "Test": {"tel": "PMS_Tel1", "postalOptIn": 0, "postal": "S3_Postal1", "email": "PMS_EMail1"}, "vorname": "PMS_Vorname1" }}';
print_r(json_decode($string, true));
Which returns an array:
Array
(
[userData] => Array
(
[geburtsdatum] => PMS_2018-01-01
[anrede] => PMS_Herr
[ID] => 1
[nachname] => PMS_Nachname1
[Test] => Array
(
[tel] => PMS_Tel1
[postalOptIn] => 0
[postal] => S3_Postal1
[email] => PMS_EMail1
)
[vorname] => PMS_Vorname1
)
)
I'm trying to decode json array to php array using json_decode, but it's displaying a blank page
Here's the json array
[["id":"2","name":"Sam Nju","photo":"1510074080885.jpg","qty":"10","price":"10000.00"],["id":"3","name":"Daniel","photo":"1510074047056.jpg","qty":"0","price":"40000.00"]]
Here's the code to decode json
$json = file_get_contents('http://localhost/example/index.php/destinations/json');
$data = json_decode($json,true);
$names = $data['result'];
echo "<pre>";
echo $names;
print_r($names);
Thanks
For obtaining proper JSON using json_decode() and json_encode() follow these guidelines:
json_decode() :
This function only works with UTF-8 encoded strings.
Returns the value encoded in json in appropriate PHP type. Values true, false and null are returned as TRUE, FALSE and NULL respectively. NULL is returned if the json cannot be decoded or if the encoded data is deeper than the recursion limit.
The key and value must be enclosed in double quotes single quotes are not valid.
Your JSON:
[["id":"2","name":"Sam Nju","photo":"1510074080885.jpg","qty":"10","price":"10000.00"],["id":"3","name":"Daniel","photo":"1510074047056.jpg","qty":"0","price":"40000.00"]]
apears to be invalid. Arrays use [] while objects use {}.
This is an example of how a proper PHP array structure would look like prior to doing json_encode() (before sending):
// array structure in PHP to get proper JSON
Array ( [0] => Array ( [id] => 2 [name] => Sam Nju [photo] => 1510074080885.jpg [qty] => 10 [price] => 10000.00 ) [1] => Array ( [id] => 3 [name] => Daniel [photo] => 1510074047056.jpg [qty] => 0 [price] => 40000.00 ) )
which was obtained using the following:
json_decode('[{"id":"2","name":"Sam Nju","photo":"1510074080885.jpg","qty":"10","price":"10000.00"},{"id":"3","name":"Daniel","photo":"1510074047056.jpg","qty":"0","price":"40000.00"}]', true)
which would mean doing this:
$myArray = array();
$firstPerson = array();
$secondPerson = array();
$firstPerson['id'] = 2;
$firstPerson['name'] = "Sam Nju";
// ...
$secondPerson['id'] = 3;
$firstPerson['name'] = "Daniel";
// ...
array_push($myArray, $firstPerson);
array_push($myArray, $secondPerson);
// or $myArray[0] = $firstPerson; and $myArray[1] = $secondPerson;
While valid JSON would look like this:
{{"id":"2","name":"Sam Nju","photo":"1510074080885.jpg","qty":"10","price":"10000.00"},{"id":"3","name":"Daniel","photo":"1510074047056.jpg","qty":"0","price":"40000.00"}}
If you are getting the data from a database you might want to use something like this:
$result = mysqli_query($con, "SELECT .... // database query, $con is connection variable
$myArray = array();
while($row = mysqli_fetch_array($result))
{
$tempArray = array();
$tempArray['id'] = $row[0];
$tempArray['name'] = $row[1];
$tempArray['photo'] = $row[2];
// ...
array_push($myArray, $tempArray);
}
// use print_r($myArray); to test it out.
Although your code looks correct, your JSON data is invalid. Objects are enclosed by {}, not []. Replace the JSON with this, and it should work.
[
{
"id": "2",
"name": "Sam Nju",
"photo": "1510074080885.jpg",
"qty": "10",
"price": "10000.00"
},
{
"id": "3",
"name": "Daniel",
"photo": "1510074047056.jpg",
"qty": "0",
"price": "40000.00"
}
]
Also above answer already mentioned it:
Your JSON is invalid. You can check this e.g. with an JSON linter like https://jsonlint.com/
Plus, you're referencing names with $names = $data['result'];. However, in your provided JSON there is no array (or better object), with key "result".
You may look up your PHP's error log file to understand where the problem lies.
this is what i get as a string from a feed finder url (JSON Encoded):
{
"updated": 1265787927,
"id": "http://www.google.com/reader/api/0/feed-finder?q\u003dhttp://itcapsule.blogspot.com/\u0026output\u003djson",
"title": "Feed results for \"http://itcapsule.blogspot.com/\"",
"self": [{
"href": "http://www.google.com/reader/api/0/feed-finder?q\u003dhttp://itcapsule.blogspot.com/\u0026output\u003djson"
}],
"feed": [{
"href": "http://itcapsule.blogspot.com/feeds/posts/default"
}]
}
How can i decode it using json_decode() function in php and get the last array element ("feed") ? i tried it with the following code but no luck
$json = file_get_contents("http://www.google.com/reader/api/0/feed-finder?q=http://itcapsule.blogspot.com/&output=json");
$ar = (array)(json_decode($json,true));
print_r $ar;
Please help ..
$array = json_decode($json, true);
$feed = $array['feed'];
Note that json_decode() already returns an array when you call it with true as second parameter.
Update:
As the value of feed in JSON
"feed":[{"href":"http://itcapsule.blogspot.com/feeds/posts/default"}]
is an array of objects, the content of $array['feed'] is:
Array
(
[0] => Array
(
[href] => http://itcapsule.blogspot.com/feeds/posts/default
)
)
To get the URL you have to access the array with $array['feed'][0]['href'] or $feed[0]['href'].
But this is basic handling of arrays. Maybe the Arrays documentation helps you.
I have a problem.
For a mistake I have a lot of not valid JSON strings like this:
{
"d": {
"results": [
{
"__metadata": {
"uri": "https://api.datamarket.azure.com/Data.ashx/Bing/Search/Web?Query=u0027non supporting iframesu0027&Market=u0027it-ITu0027&Adult=u0027Offu0027&Options=u0027DisableLocationDetectionu0027&WebSearchOptions=u0027DisableQueryAlterationsu0027&$skip=0&$top=1",
"type": "WebResult"
},
"ID": "7858fc9f-6bd5-4102-a835-0fa89e9f992a",
"Title": "something good",
"Description": "something "WRONG" here!",
"DisplayUrl": "www.devx.com/Java/Article/27685/1954",
"Url": "http://www.devx.com/Java/Article/27685/1954"
}
],
"__next": "https://api.datamarket.azure.com/Data.ashx/Bing/Search/Web?Query=u0027non%20supporting%20iframesu0027&Market=u0027it-ITu0027&Adult=u0027Offu0027&Options=u0027DisableLocationDetectionu0027&WebSearchOptions=u0027DisableQueryAlterationsu0027&$skip=50"
}
}
As you can see the field Description contains a bad string (" into "), so I'm not able to parse the json using php's json_decode, infact it returns NULL.
I've 1 million of wrong json, much more big than this (10 times).
How can I do in php?
In your case you could exploit the fact that strings in json could not be over a line. That is a snappy point to grab with s multi-line aware search and replace with a regular expression function like preg_match_callback in PHP.
/^\s+"[a-z_"]+": "([^"]*".*)",?$/mi
Whitespace at the beginning of the line; member-name in form of a valid name (only characters and underscore here) as a string; the : and then the broken string until the end of the line optionally followed by a comma ,?.
This regex already matches only invalid lines. However if your json also contains a valid string with \" inside, this regex does not really work.
So it's also good to place some checks that the replacement would do what it is intended.
$like = '... json-like but broken json string as in question ...';
// Fixing #1: member strings containing double-quotes on the same line.
$fix1Pattern = '/^(\s+"[a-z_]+": ")([^"]*".*)(",?)$/mi';
$fix1Callback = function ($matches) {
list($full, $prefix, $string, $postfix) = $matches;
$fixed = strtr($string, ['"' => '\"']);
if (!is_string(json_decode("\"$fixed\""))) {
throw new Exception('Fix #1 did not work as intended');
}
return "$prefix$fixed$postfix";
};
// apply fix1 onto the string
$buffer = preg_replace_callback($fix1Pattern, $fix1Callback, $like);
// test if it finally works
print_r(json_decode($buffer));
Keep in mind that this is limited. You might need to learn about regular expressions first which is a world of it's own. But the principle is often very similar: You search the string for the patterns that are the broken parts and then you do some string manipulation to fix these.
If the json string is much more broken, then this needs even more love, probably not to be easily solved with a regular expression alone.
Exemplary output for the code-example and the data provided:
stdClass Object
(
[d] => stdClass Object
(
[results] => Array
(
[0] => stdClass Object
(
[__metadata] => stdClass Object
(
[uri] => https://api.datamarket.azure.com/Data.ashx/Bing/Search/Web?Query=u0027non supporting iframesu0027&Market=u0027it-ITu0027&Adult=u0027Offu0027&Options=u0027DisableLocationDetectionu0027&WebSearchOptions=u0027DisableQueryAlterationsu0027&$skip=0&$top=1
[type] => WebResult
)
[ID] => 7858fc9f-6bd5-4102-a835-0fa89e9f992a
[Title] => something good
[Description] => something "WRONG" here!
[DisplayUrl] => www.devx.com/Java/Article/27685/1954
[Url] => http://www.devx.com/Java/Article/27685/1954
)
)
[__next] => https://api.datamarket.azure.com/Data.ashx/Bing/Search/Web?Query=u0027non%20supporting%20iframesu0027&Market=u0027it-ITu0027&Adult=u0027Offu0027&Options=u0027DisableLocationDetectionu0027&WebSearchOptions=u0027DisableQueryAlterationsu0027&$skip=50
)
)