I'm trying to decode some basic JSON data from Mintpal.com (https://www.mintpal.com/api)
The raw data looks like:
[
{
"market_id": "152",
"coin": "VeriCoin",
"code": "VRC",
"exchange": "BTC",
"last_price": "0.00008512",
"yesterday_price": "0.00009300",
"change": "-8.47",
"24hhigh": "0.00009450",
"24hlow": "0.00008050",
"24hvol": "13.153",
"top_bid": "0.00008063",
"top_ask": "0.00008591"
}
]
I just want to pull bits off this information out and assign them to variables. I use the below code with another near identical JSON output and it works fine.
//GET MINTPAL JSON DATA
$url = "https://api.mintpal.com/v1/market/stats/VRC/BTC";
$contents = file_get_contents($url);
$json = json_decode($contents);
//GET 'LAST BID' INFO
$lastBid = $json->code;
The previous raw JSON that works with the above code looks exactly the same, except for not being encased in '[...]' as the Mintpal one is.
{
"success": true,
"message": "",
"result": [
{
"MarketName": "BTC-LTC",
"High": 0.01126000,
"Low": 0.01060000,
"Volume": 442.30927821,
"Last": 0.01061100,
"BaseVolume": 4.86528601,
"TimeStamp": "2014-08-27T13:49:03.497",
"Bid": 0.01051801,
"Ask": 0.01061100,
"OpenBuyOrders": 50,
"OpenSellOrders": 116,
"PrevDay": 0.01079000,
"Created": "2014-02-13T00:00:00"
}
]
}
Any ideas on why I can't read the information this time round?
If you either did a var_dump() or a print_r() of your $json variable you should see that it is now an array starting at element 0 containing all the unique json elements.
//GET MINTPAL JSON DATA
$url = "https://api.mintpal.com/v1/market/stats/VRC/BTC";
$contents = file_get_contents($url);
$json = json_decode($contents);
pR($json);
//GET 'LAST BID' INFO
$lastBid = $json->code;
function pR($data){
echo "<pre>";
print_r($data);
echo "</pre>";
}
That yielded:
Array
(
[0] => stdClass Object
(
[market_id] => 152
[coin] => VeriCoin
[code] => VRC
[exchange] => BTC
[last_price] => 0.00008512
[yesterday_price] => 0.00009300
[change] => -8.47
[24hhigh] => 0.00009300
[24hlow] => 0.00008050
[24hvol] => 12.968
[top_bid] => 0.00008065
[top_ask] => 0.00008585
)
)
Related
I've been trying to do this for a while now and I just can't seem to get it right. One post got me very close but not quite there because my of JSON's hierarchy. (it's an assignment and this hierarchy is mandatory.)
What I do right now is submit info from one page, POST it to my php on another page, save it in an array there, json_encode that array and write that to my JSON file.
Here is my watered-down code, hopefully getting rid of most unnecessary code:
<?php
$filename = "json/exercises.json";
$filesize = filesize($filename);
$fp = fopen($filename, "r+");
#Accept the submitted form
$exLanguage = $_POST['exLanguage'];
$exTitle = $_POST['exTitle'];
$exStuff = $_POST['exStuff'];
#write to JSON with an incrementing ID
if (file_get_contents($filename) == "") {
$exercise = array (
"id" => 1,
"lang" => $exLanguage,
"title" => $exTitle,
"main_object" =>
[
"exStuff" => $exStuff
]
);
$exercise_json = json_encode($exercise, JSON_PRETTY_PRINT);
file_put_contents($filename, $exercise_json, FILE_APPEND);
} else {
#Get the last set ID
$jsonid = json_decode(fread($fp, $filesize), true);
$last = end($jsonid);
$title = prev($jsonid);
$lang = prev($jsonid);
$id = prev($jsonid);
$exercise = array (
"id" => ++$id,
"lang" => $exLanguage,
"title" => $exTitle,
"main_object" =>
[
"exStuff" => $exStuff
]
);
$exercise_json = json_encode($exercise, JSON_PRETTY_PRINT);
file_put_contents($filename, $exercise_json, FILE_APPEND);
}
?>
now what this does is if my json is empty it adds the first array correctly with the ID at 1. Then if I try to add to my json again it adds it correctly with the ID at 2. But any more attempted writes to the JSON will give me these errors:
Warning: end() expects parameter 1 to be array, null given
Warning: prev() expects parameter 1 to be array, null given
Warning: prev() expects parameter 1 to be array, null given
Warning: prev() expects parameter 1 to be array, null given
I tried doing a
$reset = reset($jsonid);
after writing to file but that didn't work, just gave me another error on the 3rd write for the reset being given a null too.
Can anyone please tell me how to get this too work? Or if there is a much easier way of getting this done?
Understand JSON format first. Its a collection of Objects which means attribute: value pair wrapped in {} and separated by comma , and then again wrapped in {} OR [] at top level.
Your JSON structure is incomplete or corrupted. What you are doing currently will create JSON in following format in your JSON file:
{ "id": 1, "lang": "as", "title": "asdsad" }
{ "id": 2, "lang": "as", "title": "asdsad" }
{ "id": 3, "lang": "as", "title": "asdsad" }
{ "id": 4, "lang": "as", "title": "asdsad" }
So json_decode will return null in this case because of invalid JSON format.
You need to keep appending your new JSON in existing JSON such that above format will become like this:
[
{ "id": 1, "lang": "as", "title": "asdsad" },
{ "id": 2, "lang": "as", "title": "asdsad" },
{ "id": 3, "lang": "as", "title": "asdsad" },
{ "id": 4, "lang": "as", "title": "asdsad" }
]
Which means your else block is incorrect. Use following code in else block:
$jsonid = json_decode(file_get_contents($filename), true);
$last = end($jsonid);
$id = $last['id'];
$jsonid[] = array (
"id" => ++$id,
"lang" => $exLanguage,
"title" => $exTitle,
"main_object" => array("exStuff" => $exStuff)
);
$exercise_json = json_encode($jsonid, JSON_PRETTY_PRINT);
file_put_contents($filename, $exercise_json, FILE_APPEND);
I hope you are not bound to use that incorrect/corrupted JSON format. That will not work with json_decode() in any case.
This question already has an answer here:
How to extract and access data from JSON with PHP?
(1 answer)
Closed 5 years ago.
I have a question about some JSON and PHP, see json below.
How can I get the number string?
{
”data”: [
{
”numbers”: [
{
”number”: "XXXX",
”type”: ””
}
]
}
]
}
Ive tried with the following but its not working:
$item['numbers'][0]->number;
Note, the $item array is ok. I just do not know what is wrong here.
EDIT:
I should point out that there was an json_decode before.
So the structure looks like this:
Array
(
[0] => Array
(
[number] => XXXX
[type] =>
)
)
print_r($item['numbers']);
This doesn't work: $item['numbers'][0]['number'];
Error: Undefined offset: 0 in
Thanks!
if you want to direct access then use this code
$items->data->numbers->number;
you can use php json_decode().it takes a JSON encoded string and converts it into a PHP variable.
<?php
$json_data = '{
"data": [
{
"numbers": [
{
"number": "11",
"Type": ""
}
]
}
]
}';
$array=json_decode($json_data,true);
echo "<pre>";
print_r($array);
echo $array["data"][0]["numbers"][0]["number"];
then output
Array
(
[data] => Array
(
[0] => Array
(
[numbers] => Array
(
[0] => Array
(
[number] => 11
[Type] =>
)
)
)
)
)
Number:11
To get the number try this :
$myJSON->data->numbers->number;
Hope this will help you out... You are trying to access which does not actually exists.
try this code snippet here
<?php
ini_set('display_errors', 1);
$month_options = '{
"data": [
{
"numbers": [
{
"number": "10",
"Type": ""
}
]
}
]
}';
$array=json_decode($month_options,true);
echo $array["data"][0]["numbers"][0]["number"];
Use the json_decode() function of PHP.
$array = json_decode('{
”data”: [
{
”numbers”: [
{
”number”: "",
”Type”: ””
}
]
}
]
}', true);
Then you could access it as $array["data"]["numbers"]["number"];
The server receives from URL post string as below:
{
"head": {
"comm": 7,
"compress": false,
"ms": 1451029423348,
"encrypt": false,
"version": 2
},
"body": {
"data1": 0,
"data2": 59,
"data3": -40,
"data4": 0,
"data5": 0,
}
}
I have PHP file as below need to receive JSON format data from URL or java app sending post to server. Using server PHP ver 5.4.45, I can't change it.
$json = file_get_contents('php://input');
$string = get_magic_quotes_gpc() ? stripslashes($json) : $json;
$object = json_decode($string);
var_dump($object);
then i want to put to array each item in to array into $data variable each fields into $data array
I always receiving NULL , What can be the problem ?
If I paste your json here: http://jsonlint.com/ it gives a "Error: Parse error on line 14:"
Maybe it helps when you remove the comma after "data5": 0,
The JSON data is not correct. Try after removing the , after "data": 0.
Correct JSON :
{
"head": {
"comm": 7,
"compress": false,
"ms": 1451029423348,
"encrypt": false,
"version": 2
},
"body": {
"data1": 0,
"data2": 59,
"data3": -40,
"data4": 0,
"data5": 0
}
}
If, as you say, $json is NULL, the comma after "data5" is only because of text that was cut to make pasted code shorter, and you're using PHP <5.6 then according to http://php.net/manual/en/wrappers.php.php it could only be that either:
you're reading php://input multiple times (if not you then maybe a framework you're using or whatever);
the sender is passing data to you as multipart/form-data, which php://input cannot read.
try this:
$json = file_get_contents('php://input');
$string = get_magic_quotes_gpc() ? stripslashes($json) : $json;
$object = json_decode($string);
By using foreach function walk thru object elements and typecast them as an array
foreach($object as $k=>$v){
$data[$k] = (array)$v;
}
and the result will be as follows:
Array
(
[head] => Array
(
[comm] => 7
[compress] =>
[ms] => 1451029423348
[encrypt] =>
[version] => 2
)
[body] => Array
(
[data1] => 0
[data2] => 59
[data3] => -40
[data4] => 0
[data5] => 0
)
)
I need to create json with multiple levels via PHP.
{
"accident": {
"dateTime": "2015-08-08T16:12:08",
"desc": "string"
},
"calculationInput": {
"idBlockCodes": [
{
"code": 51,
"value": 1
}
],
"wageRates": {
"labourRate1": 10,
"labourRate2": 11,
"labourRate3": 22,
"labourRate4": 33,
"labourRateD": 44,
"paintRate": 55
}
},
"caseNumber": "F4Q",
"vehicle": {
"adminData": {
"firstRegDate": "2015-07-08",
"numberPlate": "MI214AF"
},
"identification": {
"vin": "VF7S6NFZF56215577"
},
"owner": {
"city": "Praha",
"country": "CZE",
"email": "mail#mail.com",
"name": "Fero Taraba",
"phone": "777111222",
"phone2": "999555333",
"postCode": "07101",
"street": "Kukureliho 18"
}
}
}
I actuyltry this and it's possible for me to create single level json, with other words:
$data = array (
"caseNumber" =>"F4Q"
);
and then just easy:
$data_json= json_encode($data);
But can someone explain me how can I do this second or even 3th level tree to convert to JSON?
I will really appriciate your help guys. Thanks
EDIT:
Most of the answers really lead me right way, only problem now is this part:
"idBlockCodes": [
{
"code": 51,
"value": 1
}
],
where there is [ ] which represent some list of blockCodes. Any idea what to do with this ? :)
What is your question exactly?
You can create a array and then just encoding it to json?
$data = array(
'Key 1' => array(
'Key 2 - Key 1' => array(
'Key 3 - Key 1' => array()
)
)
);
echo json_encode($data);
Just use associative arrays
$data = array (
"caseNumber" =>"F4Q",
"vehicle" => array (
"adminData"=>
array(
"firstRegDate"=> "2015-07-08",
"numberPlate"=> "MI214AF"
),
"identification" =>
array(
"vin"=> "VF7S6NFZF56215577"
)
)
);
print out
{"caseNumber":"F4Q","vehicle":{"adminData":{"firstRegDate":"2015-07-08","numberPlate":"MI214AF"},"identification":{"vin":"VF7S6NFZF56215577"}}}
Use associative Arrays:
$data = array (
"caseNumber" =>"F4Q",
"vehicle" => array (
"adminData"=>
array(
"firstRegDate"=> "2015-07-08",
"numberPlate"=> "MI214AF"
),
"identification" =>
array(
"vin"=> "VF7S6NFZF56215577"
)
)
);
echo json_encode($data)
you get your brackets by putting an additional array around your object.
$data = array("idBlockCodes" => array(
array(
"code" => 51,
"value" => 1
)
)
);
print json_encode($data);
For you to convert all of your data to array:
You must first use json_encode();
$a = json_encode($yourData);
And then decode it:
$b = json_decode($a, true);
echo '<pre>';
print_r($b); //print it
It displays associated arrays with it
I have JSON that looks like this (shortened for readability):
{
"heroes": [
{
"name": "antimage",
"id": 1,
"localized_name": "Anti-Mage"
},
{
"name": "axe",
"id": 2,
"localized_name": "Axe"
},
{
"name": "bane",
"id": 3,
"localized_name": "Bane"
}
]
}
I have a PHP variable that is equal to one of the three ids. I need to search the JSON for the id and return the localized name. This is what I’m trying so far.
$heroid = $myplayer['hero_id'];
$heroes = file_get_contents("data/heroes.json");
$heroesarray = json_decode($heroes, true);
foreach ($heroesarray as $parsed_key => $parsed_value) {
if ($parsed_value['id'] == $heroid) {
$heroname = $parsed_value['localized_name'];
}
}
Easy. Just use json_decode(). Explanation follows the code at the bottom.
// First set the ID you want to look for.
$the_id_you_want = 2;
// Next set the $json.
$json = <<<EOT
{
"heroes": [
{
"name": "antimage",
"id": 1,
"localized_name": "Anti-Mage"
},
{
"name": "axe",
"id": 2,
"localized_name": "Axe"
},
{
"name": "bane",
"id": 3,
"localized_name": "Bane"
}
]
}
EOT;
// Now decode the json & return it as an array with the `true` parameter.
$decoded = json_decode($json, true);
// Set to 'TRUE' for testing & seeing what is actually being decoded.
if (FALSE) {
echo '<pre>';
print_r($decoded);
echo '</pre>';
}
// Now roll through the decoded json via a foreach loop.
foreach ($decoded as $decoded_array_key => $decoded_array_value) {
// Since this json is an array in another array, we need anothe foreach loop.
foreach ($decoded_array_value as $decoded_key => $decoded_value) {
// Do a comparison between the `$decoded_value['id']` and $the_id_you_want
if ($decoded_value['id'] == $the_id_you_want) {
echo $decoded_value['localized_name'];
}
}
}
Okay, the reason my first try at this did not work—and neither did yours—is your JSON structure was nested one more level deep that what is expected. See the debugging code I have in place with print_r($decoded);? This is the output when decoded as an array:
Array
(
[heroes] => Array
(
[0] => Array
(
[name] => antimage
[id] => 1
[localized_name] => Anti-Mage
)
[1] => Array
(
[name] => axe
[id] => 2
[localized_name] => Axe
)
[2] => Array
(
[name] => bane
[id] => 3
[localized_name] => Bane
)
)
)
First you have an array to begin with which could equate to $decoded[0] and then below that you have another array that equates to $decoded[0]['heroes'] and then in there is the array that contains the values which is structured as $decoded[0]['heroes'][0], $decoded[0]['heroes'][1], $decoded[0]['heroes'][2].
But the key to solving this was the print_r($decoded); which helped me see the larger structure of your JSON.
json_decode() takes a JSON string and (if the second parameter is true) turns it into an associate array. We then loop through this data with a foreach until we find the hero you want.
$json = ''; // JSON string
$data = json_decode($json, true);
foreach($data['heroes'] as $hero) {
if($hero['id'] === 2) {
var_dump($hero['localized_name']);
// Axe
// This will stop the loop, if you want to keep going remove this line
break;
}
}