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 ?
Related
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
)
)
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',
),
);
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"
}
]
}
I have a rather big json file with coordinates in the following format
"[[3.2,1],[4.8,2]]"
which represents (3.2,1) and (4.8,2)
I'm using these coördinates to generate a D3 geographic map, but when php is modelling this information into a geoJSONobject I encounter the following error:
I need to transform the coordinates into a array for which I use json_decode. However:
json_decode("[[3.2,1],[4.8,2]]")
returns
Array
(
[0] => Array
(
[0] => 3
[1] => 1
)
[1] => Array
(
[0] => 4
[1] => 2
)
)
Where I lose the decimals. How can I prevent this?
Edit:
{"type": "FeatureCollection",
"features": [{
"type": "Feature",
"geometry": {
"type": "Polygon",
"coordinates": "[[[8.7, 11], [8.89, 12.13],[9.27, 12.13], [9.9, 12], [9.7, 10.8], [8.7, 11]]]"
},
"properties": {
"name": "04",
"count": "25"
}
}]
}
This is an example of the data I'm getting as output. (It is supposed to represent a map of rooms which are get a density color by its usage)
I am able to parse this using jQuery.parseJSON(data), but running the following D3 code generates the weirdest errors:
val(svgname).append("g")
.selectAll("path")
.data(geoJSONobject.features)
.enter().append("path")
.attr("d", path)
...
I think it's because of the quotes around the array of coordinates.
Edit (2) - actual solution
The solution I accepted was a workaround, but the true issue was localized php-settings. using:
echo json_encode($dataset, JSON_NUMERIC_CHECK);
in the php-file, all the issues were resolved. Though I'd update the question since it is still being looked at (if anyone would encouter the issue)
I had the same problem. I solved it using the followin regex
SOLUTION 1
$yourJsonVariable = preg_replace('/:\s*(\-?\d+(\.\d+)?([e|E][\-|\+]\d+)?)/', ': "$1"', $yourJsonVariable);
Convert it into array
$array = json_decode($yourJsonVariable, true);
Credits goes to this SO LINK
SOLUTION 2
You can set ini_set('precision',1);
SOLUTION 3
$decoded = json_decode($encoded, true, null, JSON_BIGINT_AS_STRING);
NOTE: The Last solution will work only for PHP > 5.4
You might want to take a look at this Blog
Just wrap the values in quotes: json_decode('[["3.2","1"],["4.8","2"]]');
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'];