I am trying to take a json object stored in a textarea and convert it into a php array. I assign the value of the textarea to variable like $data = $_POST[‘data’] . When I submit the value of the text I use json_decode($data, true) to convert from JSON Object to php array. But nothing happens. It seems like nothing is assigned. How can I achieve the above?
EDIT: I have added quotes and made the suggestion below and is not working: DEMO
PHP
if(isset($_POST['submit'])) {
$data = $_POST['data'];
$personArray = json_decode($data, true);
print_r($personArray);
}
HTML
<textarea name="data">[{
"firstName": "Jenny",
"lastName": "LaRusso",
"phone": "(555) 121-2121",
"alt_phone": "(555) 123-4567",
"main1": false,
"main2": true
}, {
"firstName": "Sensei",
"lastName": "Miyagi",
"phone": "(555) 444-2222",
"alt_phone": "(555) 999-1212",
"main1": true,
"main2": false
}]</textarea>
I think in proper JSON, the keys (like firstName) need also be enclosed in quotes.
Change your PHP code to
if(isset($_POST['data'])) {
$data = $_POST['data'];
$data = stripslashes($data); //Stripslashes removes all backslashes :)
$personArray = json_decode($data, true);
print_r($personArray);
}
Your JSON object should be this way inside the textarea
[{
"firstName": "Jenny",
"lastName": "LaRusso",
"phone": "(555) 121-2121",
"alt_phone": "(555) 123-4567",
"main1": false,
"main2": true
}, {
"firstName": "Sensei",
"lastName": "Miyagi",
"phone": "(555) 444-2222",
"alt_phone": "(555) 999-1212",
"main1": true,
"main2": false
}]
Happy Coding :)
There does not seem to be anything wrong with your PHP code.
For debugging, after setting $personArray, try adding these two lines:
var_dump($data);
var_dump($personArray);
This should lead to why you are having trouble.
Here you can see what each return type means(if $returnArray is equal to false): http://php.net/json_decode
Related
My JSON data is given below. It does not have [] or separated by comma which make it difficult for me to decode.
$jsondata =
'{"firstname": "user1", "lastname": "user1", "phonenumber": "12314", "notes": "[]", "lastvisited": "2021-05-12 21:49:15"}
{"firstname": "user2", "lastname": "user2", "phonenumber": "12345", "notes": "[]", "lastvisited": "2021-04-24 20:48:58"}';
My try:
$jsonans = json_decode($jsondata, true);
print_r($jsonans);
Any code suggestion is appreciated.
Thanks,
Your best bet is to get valid JSON. If this was stored somewhere as invalid and these are the only problems then just fix them:
$jsondata = '['.preg_replace('/}\s+{/', '}, {', $jsondata).']';
$result = json_decode($jsondata, true);
If you're sure that there is only one space between } and { then faster than regex:
$jsondata = '['.str_replace('} {', '}, {', $jsondata).']';
Then just loop $result and https://www.php.net/manual/en/function.fputcsv.php
I have a string that i get from an API and i wish i could put it in a array so i could check the values that came from the return.
String return example:
{
"code":"000",
"message":"XXX",
"date":"2018-05-17",
"hour":"09:16:09",
"revision":"",
"server":"XX",
"content":{
"nome":{"info":"SIM","conteudo":[{"field1":"XXXX","field2":"XX"}]}
}
}
What I need:
echo $string['code'];
Javascript has no problem with JSON encode command. But how can I do it with PHP?
First of all your JSON data seems to be invalid (Some brackets missing). It needs to be like this:-
{
"code": "000",
"message": "XXX",
"date": "2018-05-17",
"hour": "09:16:09",
"revision": "",
"server": "XX",
"content": {
"nome": {
"info": "SIM",
"conteudo": [{
"field1": "XXXX",
"field2": "XX"
}]
}
}
}
Now You need to decode this JSON data and then get data based on the index
$array = json_decode($json,true);
echo $array['code'];
Output:-https://eval.in/1005949
You can decode the JSON string to Array in PHP.
$str = '{"code":"000","message":"XXX","date":"2018-05-17","hour":"09:16:09","revision":"","server":"XX","content":{"nome":{"info":"SIM","conteudo":[{"field1":"XXXX","field2":"XX"}]}';
$decodedValue = json_decode($str, true);
var_dump($decodedValue);
Your example string is not valid json, you are missing some closing brackets.
This should be the correct way:
'{"code":"000","message":"XXX","date":"2018-05-17","hour":"09:16:09","revision":"","server":"XX","content":{"nome":{"info":"SIM","conteudo":[{"field1":"XXXX","field2":"XX"}]}}}'
As for your question. in PHP you can easily use json_decode
Example:
<?php
$json = '{"code":"000","message":"XXX","date":"2018-05-17","hour":"09:16:09","revision":"","server":"XX","content":{"nome":{"info":"SIM","conteudo":[{"field1":"XXXX","field2":"XX"}]}}}';
$decoded_json = json_decode($json, true);
echo $decoded_json['code'];
You can see it working here
I have JSON Object which I have encoded like so
{
"id": "",
"steps": [
{
"target": "purchase_order_items_itemmaster_id",
"title": "",
"placement": "",
"content": "",
"xoffset": "",
"yoffset": ""
}
]
}
$JSONData = json_encode($finalData,JSON_PRETTY_PRINT);
I am taking this JSON data and storing it in a file like so
File::put("path","var tour = \n [ \n\t $JSONData \n ];");
which looks something like this in the file
var tour =
[
{
"id": "",
"steps": [
{
"target": "purchase_order_items_itemmaster_id",
"title": "",
"placement": "",
"content": "",
"xoffset": "",
"yoffset": ""
}
]
}
];
Now I am reading it back form the second line like so
[
{
"id": "",
"steps": [
{
"target": "purchase_order_items_itemmaster_id",
"title": "",
"placement": "",
"content": "",
"xoffset": "",
"yoffset": ""
}
]
}
];
The problem is when I want to decode it back it doesn't happen,this is how I am trying to do that,
$lines = file_get_contents("path",NULL,NULL,10);
$a = json_decode($lines);
Now according to expected output the $a should have the decoded data but it has null.
Can someone point out the mistake?
I believe the issue is the semicolon at the end of the JSON you've read back in from the file. Try chopping that off before attempting json_decode:
$a = json_decode(rtrim($lines, ";"));
pass the second parameter true for recursively decoding
$a = json_decode(chop($lines,";"),true);
check the php mannual here json_decode
It will be
$str = file_get_contents('http://example.com/example.json/');
$json = json_decode($str, true); // decode the JSON into an associative array
See the post
Parsing JSON file with PHP
try to save data in file like
$fp = fopen('path', 'w');
fwrite($fp, json_encode($JSONData)); //if $JSONData is in string
fclose($fp);
instead of
File::put("path","var tour = \n [ \n\t $JSONData \n ];");
//and read like
// Read JSON file
$json = file_get_contents('path');
//Decode JSON
$json_data = json_decode($json,true);
//Print data
print_r($json_data);
I want preserve original value of target field and use json_decode to use following string as object:
{
"translatorID": "f4a5876a-3e53-40e2-9032-d99a30d7a6fc",
"label": "ACL",
"creator": "Nathan Schneider",
"target": "^https?://(www[.])?aclweb\\.org/anthology-new/[^#]+",
"minVersion": "1.0.7",
"maxVersion": "",
"priority": 100,
"browserSupport": "gcs",
"inRepository": true,
"translatorType": 4,
"lastUpdated": "2012-01-01 01:42:16"
}
What you can do before parsing with json_decode is:
$string = str_replace('\\', '\\\\\\\\', $string);
var_dump(json_decode($string, true));
This must be a bug in the json parser.
The method is not very clean but at least you're getting your results.
Did you try stripping the slashes off?
This worked for me :
$string = '{
"translatorID": "f4a5876a-3e53-40e2-9032-d99a30d7a6fc",
"label": "ACL",
"creator": "Nathan Schneider",
"target": "^https?://(www[.])?aclweb\.org/anthology-new/[^#]+",
"minVersion": "1.0.7",
"maxVersion": "",
"priority": 100,
"browserSupport": "gcs",
"inRepository": true,
"translatorType": 4,
"lastUpdated": "2012-01-01 01:42:16"
}';
var_dump( json_decode(stripslashes ($string)));
I have json from stripe and I am trying to decode it json_decode.
I am not getting an error. Just nothing is returning. I am getting the data back from stripe, I just cant decode it.
{
"created":1326853478,
"data":{
"object":{
"amount":4500,
"card":{
"country":"US",
"cvc_check":"pass",
"exp_month":7,
"exp_year":2014,
"fingerprint":"9aQtfsI8a17zjEZd",
"id":"cc_00000000000000",
"last4":"9782",
"object":"card",
"type":"Visa"
},
"created":1322700852,
"currency":"usd",
"disputed":false,
"fee":0,
"id":"ch_00000000000000",
"livemode":false,
"object":"charge",
"paid":true,
"refunded":true
}
},
"id":"evt_00000000000000",
"livemode":false,
"type":"charge.refunded"
}
// retrieve the request's body and parse it as JSON
$body = #file_get_contents('php://input');
$event_json = json_decode($body,true);
print_r($event_json);
Any ideas?
The php://input stream allows you to read raw data from the request body. This data will be a string and depending on what sort of values are in the request, will look something like:
"name=ok&submit=submit"
This is not JSON and therefore won't decode as JSON the way you expect.The json_decode() function returns null if it can't be decoded.
Where are you getting the JSON you posted above? That is the value you need to pass into json_decode().
If JSON is being passed in the request, like in the instance of callbacks, you would still need to parse that portion out to get just the JSON. If the php://input stream gives you name=ok&submit=submit&json={"created": 1326853478} then you'd have to parse it out. You can use this function from the PHP manual to seperate the values to work like the $_POST array:
<?php
// Function to fix up PHP's messing up POST input containing dots, etc.
function getRealPOST() {
$pairs = explode("&", file_get_contents("php://input"));
$vars = array();
foreach ($pairs as $pair) {
$nv = explode("=", $pair);
$name = urldecode($nv[0]);
$value = urldecode($nv[1]);
$vars[$name] = $value;
}
return $vars;
}
?>
To use it:
$post = getRealPOST();
$stripe_json = $post['json'];
$event_json = json_decode($stripe_json);
Here, I ran this:
<?php
$data = '{ "created": 1326853478, "data": { "object": { "amount": 4500, "card": { "country": "US", "cvc_check": "pass", "exp_month": 7, "exp_year": 2014, "fingerprint": "9aQtfsI8a17zjEZd", "id": "cc_00000000000000", "last4": "9782", "object": "card", "type": "Visa" }, "created": 1322700852, "currency": "usd", "disputed": false, "fee": 0, "id": "ch_00000000000000", "livemode": false, "object": "charge", "paid": true, "refunded": true } }, "id": "evt_00000000000000", "livemode": false, "type": "charge.refunded" }';
$arr = json_decode($data, true);
print_r($arr);
?>
And it worked. So, theoretically you should be able to use:
<?php
$arr = json_decode(file_get_contents('php://input'), true);
print_r($arr);
?>
As Ignacio Vazquez-Abrams said, don't use the '#' character because it obscures error messages and makes it harder to debug.
I would also check what version of PHP you have. json_decode() is only available on version 5.2.0 and later.