echo an array data from json decode - php

I want to echo an array data from json decode result, so I have tried both the file_get_contents and also curl which works.
This is the response I get from the server which is json output..
{"Servers": {
"lastChangedDate": null,
"ServersList": [
{
"online": "The server is UP",
"offline": "The server is DOWN",
"maintainace": "The server is currently in maintenance mode",
"location": "EU",
"ip": "x.x.x.x"
},
{
"online": "The server is UP",
"offline": "The server is DOWN",
"maintainace": "The server is currently in maintenance mode",
"location": "US",
"ip": "x.x.x.x"
}
]
}}
now then the output will be an array like this after decoding it..
Array (
[Servers] => Array (
[lastChangedDate] =>
[ServersList] => Array (
[0] => Array (
[online] => The server is UP
[offline] => The server is down
[maintenance] => The server is currently in maintenance mode
[location] => EU
[ip] => x.x.x.x
)
[1] => Array (
[online] => The server is UP
[offline] => The server is DOWN
[maintenance] => The server is currently in maintenance mode
[location] => US
[ip] => x.x.x.x
)
)
)
)
Here is my php code
<?php
$request = file_get_contents("test.json");
$input = json_decode($request, true);
echo $input['Servers']['lastChangedDate']['ServersList'][0]['online'];
?>
demo with print_r ($input); instead of echo http://phpad.org/run/1666334020
So in my main page I want to output to be like this http://codepen.io/anon/pen/jEEPMG.html

Entries $input['Servers']; and $input['lastChangedDate']; are on the same level in the array, so you can't access$input['Servers']['lastChangedDate'].
I think you're trying to do:
$input['Servers']['ServersList'][0]['online'];

in the json you posted above 'lastChangedDate' is null means you can't access it with
$input['Servers']['lastChangedDate']['ServersList'][0]['online'];
First you should find why lastChangedDate is null.
$input['Servers']['lastChangedDate']['ServersList'][0]['online'];
The bold text is where the access conflict begins. PHP should also output you an error like "Undefined index: ServerList" so you need to first fill lastChangedDate to make further requests to its content
Could it be you wanted to access
$input['Servers']['ServersList'][x]['online'];

Related

Python to PHP | String to Multidimensional Json Object To Array

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
)
)

How to convert JSON string to PHP object or array creation *code* [duplicate]

This question already has answers here:
print an array as code
(4 answers)
Closed 4 years ago.
FIRSTLY: This is a totally different question - How to convert JSON string to array
MY QUESTION...
I have a valid JSON string assigned to a php variable, $json.
I know that I can run it into json_decode($json, true); to parse into a php array at runtime, however I want to go a step beyond and convert this into a reusable php array code string, which can be simply copied and pasted into a php script, like $array = 'php array code here'.
For those who will inevitably ask "why?", an example:
to copy an example JSON endpoint parameter from an API's docs, then quickly convert to php array string code to paste into a test script as a valid test parameter for making a POST request
I know that I can do this:
$json = '
[
{
"ID": "1",
"Name": "Test One"
},
{
"ID": "2",
"Name": "Test Two"
}
]';
echo '<pre>';
echo '$phpArray = ' . print_r(json_decode($json));
echo '</pre>';
exit;
Which gets you close...
$phpArray = Array
(
[0] => stdClass Object
(
[ID] => 1
[Name] => Test One
)
[1] => stdClass Object
(
[ID] => 2
[Name] => Test Two
)
)
But there is of course still some work to do... currently I would copy this into Sublime Text or some other similar text manipulation tool and just use find/replace or regex find/replace in some cases. But what I am looking for is a quicker, more elegant solution whereby I could literally copy+paste that JSON into some script (or anywhere!), and run it to get this:
$phpArray = [
0 => [
'ID' => 1,
'Name' => 'Test One',
],
1 => [
'ID' => 2,
'Name' => 'Test Two',
],
];
Has someone created a good tool to do this already somewhere? I couldn't find anything. I am open to ANY elegant solution and will happily upvote any answer that is an improvement on this rudimentary means of bridging from the JSON to a PHP object / array creation code. Thanks!
<?php
$json = '
[
{
"ID": "1",
"Name": "Test One"
},
{
"ID": "2",
"Name": "Test Two"
}
]';
echo '$output = '.var_export(json_decode($json, true), true).';';
Output:
$output = array (
0 =>
array (
'ID' => '1',
'Name' => 'Test One',
),
1 =>
array (
'ID' => '2',
'Name' => 'Test Two',
),
);

Php - json_decode returns null [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
I am trying to decode json string that looks like the one below with json_decode php function:
"{id:"1",fields:[{id:"1",value:"asdasd"},{id: "2",value:"asdasd"},{id:"3",value:"asdasd"}]}"
I have tried various options from this question. Like:
$foo = utf8_encode($json_string);
$data = json_decode($foo, true);
Or:
json_decode(str_replace ('\"','"', $json_string), true);
Even with:
json_decode( preg_replace('/[\x00-\x1F\x80-\xFF]/', '', $json_string), true );
But, everything I try I always get null.
Why is that?
First of all, your JSON is invalid. You should always first validate your JSON before asking with any JSON lint tool, which would tell you exactly where and what the error is.
Also, you should always check for errors when handling JSON in PHP. You can check out the json_last_error function's official documentation on how to properly perform the validation.
$json = 'your_json_string';
$array = json_decode($json, true);
if (json_last_error()) {
die('Invalid JSON provided!');
}
printf('<pre>Valid JSON output: %s</pre>', print_r($array, true));
Worth mentioning: since PHP 7.3 a JSON_THROW_ON_ERROR option was added so the code can be wrapped around with a try-catch block:
try {
$array = json_decode($json, true, 512, JSON_THROW_ON_ERROR);
printf('Valid JSON output: %s', print_r($array, true));
} catch (\JsonException $exception) {
printf('Invalid JSON input: %s', print_r($exception, true));
}
Working example.
<?php
$data='{
"id": "1",
"fields": [{
"id": "1",
"value": "asdasd"
}, {
"id": "2",
"value": "asdasd"
}, {
"id": "3",
"value": "asdasd"
}]
}';
$dataNew=json_decode($data,true);
echo '<pre>';
print_r($dataNew);
Your json was not valid. The json-keys need to be inside double-quotes. After that json_decode will work fine.
Output is:
Array
(
[id] => 1
[fields] => Array
(
[0] => Array
(
[id] => 1
[value] => asdasd
)
[1] => Array
(
[id] => 2
[value] => asdasd
)
[2] => Array
(
[id] => 3
[value] => asdasd
)
)
)
Your JSON returns Null because in JSON, the keys should be string.Your JSON format is incorrect and hence returns Null.
Try rewriting it as:
{
"id":"1",
"fields":[
{
"id":"1",
"value":"asdasd"
},
{
"id": "2",
"value":"asdasd"
},{
"id":"3",
"value":"asdasd"
}
]
}

PHP & JSON Decoding

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
)
)

Issue with JSON and jQuery Iteration

I'm pretty sure it's an obvious error somewhere on this - but let me explain what I'm donig :
I'm calling a PHP file via jQuery as follows :
$.getJSON("/phpincs/getbucket.php?awskey="+awskey+"&awssecret="+awssecret+"&bucket="+bucket,
function(json){
$.each(json,function(i,item){
$(new Option(item.name,item.name)).appendTo('#bucket_contents_0');
});
}
and the JSON file it returns is as follows :
Array
(
[bt_shop.png] => Array
(
[name] => bt_shop.png
[time] => 1260393948
[size] => 156985
[hash] => 8a4eba621d5e08b84c962a0ad21ec2ae
)
[me_profile.jpg] => Array
(
[name] => me_profile.jpg
[time] => 1260393952
[size] => 2714
[hash] => 4f5d185b0c671e6165902762681f098b
)
[thumbnail.aspx.jpeg] => Array
(
[name] => thumbnail.aspx.jpeg
[time] => 1260393951
[size] => 5268
[hash] => 6939efa58ff7ffcac17218ffdd0d5d8c
)
)
true
for some reason it doesn't seem to fire the function(json){} - I've stuck an alert(''); in and it doesn't do anything.
Can someone quickly explain to me what seems to be going wrong there?
Cheers,
Carl
It is more than likely not calling the callback function because it doesn't look like what you are returning is json. If you have an $variable defined that contains your array...call
echo json_encode($jsondata); exit;
At the end of your script.
I've changed the names of the inner arrays as your previous labels are going to cause problems with the dot. You will get an error like:
myArray.bt_shop is undefined
when you try to call
alert(myArray.bt_shop.png.name);
the only way it could be called is with
alert(myArray["bt_shop.png"].name);
So having changed your code a bit, this is the JSON version of your arrays...
{
"one":
{
"name": "bt_shop.png",
"time": "1260393948",
"size": "156985",
"hash": "8a4eba621d5e08b84c962a0ad21ec2ae"
},
"two":
{
"name": "me_profile.jpg",
"time": "1260393952",
"size": "2714",
"hash": "4f5d185b0c671e6165902762681f098b"
},
"three":
{
"name": "thumbnail.aspx.jpeg",
"time": "1260393951",
"size": "5268",
"hash": "6939efa58ff7ffcac17218ffdd0d5d8c"
}
}
Then you reference your fields like this when you have the object:
myArray["two"]["name"]
myArray["two"].name
myArray.two.name
Your returned file isn't JSON. Unless you're using PHP syntax to describe your JSON object for us, you need to encode it into JSON format using json_encode.
What you call the JSON file isn't JSON. Or maybe do you use some PHP library that converts that strange format into JSONĀ ?

Categories