The examples I checked seems simple but I can't figure it out what I'm doing wrong.
I'm trying to convert and display JSON text as object array in PHP.
$json = '{"color1":red, "color2":blue, "color3":yellow}';
$arr= json_decode($json, true);
print_r($arr);
It doesn't output anything. but when I print $json, the output is just fine
Well that's not json, try
$json = '{"color1":"red", "color2":"blue", "color3":"yellow"}';
$arr= json_decode($json, true);
print_r($arr);
notice the strings are quoted with ", also see http://json.org
Related
I want to decode a JSON string. However, the value that I got is something like this string(100) "{"data":{"type":"campaign-folders","id":"d208f3171a","attributes":{"name":"My Folder"}}}".
Could anyone tell me what should I do so that I can treat this variable as a usual string ?
Use json_decode http://php.net/manual/en/function.json-decode.php
$obj = json_decode($json);
var_dump($obj);
Use json_decode ,you can solve it.
var_dump(json_decode($json, true));//check this.
here to convert JSON string to Array
$someArray = json_decode($someJSON, true);
print_r($someArray);
echo $someArray[0]["name"];
and here to convert JSON to Object
$someObject = json_decode($someJSON);
print_r($someObject);
echo $someObject[0]->name;
I have this Json Object Below, I want to extract this data and output it in PHP
{"seat_booked":"A5","0":"A5","1":"A3"}
then get them into this format
$seat_booked = "'A5', 'A5', 'A3'";
How can I do this?
I hope you are looking for this, its very simple example by using json_decode():
$string = '{"seat_booked":"A5","0":"A5","1":"A3"}';
$decoded = json_decode($string,true);
$resuiredString = '"'."'".implode("','", $decoded)."'".'"';
echo $resuiredString;
Result:
"'A5','A5','A3'"
Side Note:
I suggest you to learn about variable concatenation.
PHP Concatenation
Another solution:
$json = '{"seat_booked":"A5","0":"A5","1":"A3"}';
$decoded = array_map(
function($val) {
return "'". $val."'";
},
array_values(json_decode($json, true))
);
To get an object from a json in php you can use json_decode has explained here.
But you have another problem, your json is wrong!
If you want to represent a single dimensional array you should at least do this
["A5","A5","A3"]
Finally, using json_decode:
$obj = json_decode('["A5","A5","A3"]');
var_dump($obj);
Also, you could do something like:
{"0":"A5","1":"A5","2":"A3"}
$obj = json_decode('{"0":"A5","1":"A3", "2": "A5"}', true);
var_dump($obj);
Edit:
It's not very clear from your question if you are trying to get back an object from a json or if you just want to get a string from it.
If what you need is an string then you don't even need json, you could do this by string manipulation and/or using regex.
But just for completeness, if a quoted comma separated string is what you need you can do this:
$array = json_decode('["A5","A5","A3"]');
$str = implode("','",$array);
$str = "'" . $str . "'";
var_dump($str);
I'm trying to use a few values from this array that comes out of json_decode, but can't get any output from var_dump (which would presumably help me figure out how to access a particular value). I've tried $data[0] also from a suggestion on a similar question.
<?PHP
$json = 'callback({"geobytesinternet":"US","geobytescountry":"United States","geobytesregionlocationcode":"USWI","geobytesregion":"Wisconsin","geobytescode":"WI","geobyteslocationcode":"USWILOLA","geobytescity":"Land O Lakes","geobytescityid":"30028","geobytesfqcn":"Land O Lakes, WI, United States","geobyteslatitude":"46.154598","geobyteslongitude":"-89.396896","geobytescapital":"Washington, DC ","geobytestimezone":"-89.3969","geobytesnationalitysingular":"American","geobytespopulation":"278058881","geobytesnationalityplural":"Americans","geobytesmapreference":"North America ","geobytescurrency":"US Dollar","geobytescurrencycode":"USD","geobytestitle":"The United States"});';
$json = str_replace( 'callback(', '', $json);
$json = str_replace( ');', '', $json);
$json = '[' . $json . ']';
$data = json_decode($json);
echo '<br>decoded: ' . $data;
echo '<br><br>var_dump: ' . var_dump($data[0]);
?>
The decoded data is object array so do something like this:
$result = $data[0];
echo $result->geobytesinternet;
You are almost there, the function json_decode() takes as input json encoded string. Your string is not properly json encoded, because of this line $json = '[' . $json . ']';.
This is properly encoded json string
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
NULL is returned if the json cannot be decoded or if the encoded data is deeper than the recursion limit. See the documentation.
EDIT:
So your code should look something like this:
<?php
$json = 'callback({"geobytesinternet":"US","geobytescountry":"United States","geobytesregionlocationcode":"USWI","geobytesregion":"Wisconsin","geobytescode":"WI","geobyteslocationcode":"USWILOLA","geobytescity":"Land O Lakes","geobytescityid":"30028","geobytesfqcn":"Land O Lakes, WI, United States","geobyteslatitude":"46.154598","geobyteslongitude":"-89.396896","geobytescapital":"Washington, DC ","geobytestimezone":"-89.3969","geobytesnationalitysingular":"American","geobytespopulation":"278058881","geobytesnationalityplural":"Americans","geobytesmapreference":"North America ","geobytescurrency":"US Dollar","geobytescurrencycode":"USD","geobytestitle":"The United States"});';
//Compact a bit the code, note the ');' replacement
//str_replace() can take an array of arguments, so no need to call the function multiple times
$json = str_replace( array('callback(', ');'), '', $json);
//Get elements in a array
$data = json_decode($json);
//See what's inside the array
var_dump($data);
?>
This is a working fiddle.
I am requesting data from another website and expecting a clean json array in return.
However I am getting this instead:
<pre></pre>{"Status":"Success","Result":1}
which won't parse with json_decode();.
How do I extract the JSON array out of this data so I can parse it?
Note: I am not in control of the code I am requesting the data from.
try this
$output_array = array();
$badstr = '<pre></pre>{"Status":"Success","Result":1}';
preg_match("/{.*}/", $badstr, $output_array);
in $output_array[0] you have your json string.
Assuming that <pre></pre> is constant, then just a simple substring operation:
$badstr = '<pre></pre>{"Status":"Success","Result":1}';
$goodstr = substr($badstr, 11);
But you really should yell at the server admins for sending out bad json in the first place. There's no excuse for this kind of thing. It's probably some debug code they forgot to take out.
If you want it to work both now, and once the issue will be fixed, you can do this:
$result = '<pre></pre>{"Status":"Success","Result":1}';
if (strpos($result ,'<pre>') !== false)
{
$array = json_decode(substr($result , 11));
}
else
{
$array = json_decode($result);
}
Only remove <pre></pre>, only if it's the first thing:
$response = preg_replace('#^<pre></pre>#', '', $response);
How about simply string replace?
Like so:
$json_string = '<pre></pre>{"Status":"Success","Result":1}';
$json = str_replace("<pre></pre>", "", $json_string);
echo $json;
Output:
{"Status":"Success","Result":1}
If you don't expect any html tags in your output, you can also use strip_tags():
$not_json = '<pre></pre>{"Status":"Success","Result":1}';
$json_string = strip_tags($json);
$result = json_decode($json_string);
I'm trying to access stock Quotes through Google Finance
by doing so:
$quote = file_get_contents('http://finance.google.com/finance/info?client=ig&q=VSE:APG1L');
$json = str_replace("\n", "", $quote);
$data = substr($json, 4, strlen($json) -5);
print_r($data);
$json_output = json_decode($data, true);
print_r($json_output);
echo "\n".$json_output['l'];
json_decode suppose to give me an normal array with keys and values, but it doesn't.
If you look at json_last_error() after attempting json_decode() you'll see that you are getting:
JSON_ERROR_UTF8 Malformed UTF-8 characters, possibly incorrectly encoded
Try this:
$quote = file_get_contents('http://finance.google.com/finance/info?client=ig&q=VSE:APG1L');
$json = substr($quote, 4, -5);
$json_output = json_decode($json, true, JSON_UNESCAPED_UNICODE);
print_r($json_output);
See: http://3v4l.org/jkInl
Note that JSON_UNESCAPED_UNICODE is only available as of php 5.4
Another option would be to do...
$quote = utf8_decode($quote);
...after you fetch it. This will convert the euro symbol into a ? character. Might not be what you want, but at least you get json_decode to return an array to you.
Update: See here for more information:
PHP decoding and encoding json with unicode characters
Another solution is to "manually" replace all instances of € by \u20AC (which is the unicode character point for the Euro sign).
$quote = file_get_contents('http://finance.google.com/finance/info?client=ig&q=VSE:APG1L');
$quote = str_replace(chr(128), '\u20AC', $quote);
$json = substr($quote, 6, -3); // remove unnecessary '// [ … ]'
$json_output = json_decode($json, true);
print_r($json_output);