I receive a token in this format :
{"signature": "MEQCIFf4uQXQYR6fA48cHZMwR5K0bO/wsK5ygoCukmAfWslIAiAdc4kN1BEixxrreSI3W3x4a92+fFTw7/Ulqw9RuJPRzg\u003d\u003d","protocolVersion": "ECv1", "signedMessage": "{\"encryptedMessage\":\"HKdqg8pDCiAwaHmGeI+/7xIDXXCTSfK+/SERLh94NBX6l99w7vNgBenMCiaAGvO+nbHkmnaOnwMcq/DpRhFtCJuYjAGKA83UePYjleSgXp8AjTKUweXxpqNEVvexSeflHBQNcx4stvB7lhsCeW9SMhecebfkcgQyGlawBECXrsIWhfIRGHklC6KE18tlA0GfvsQLhKreWspHCxQjgiBDim6uR57aKzTzlTFGYK+IB1mMJbVFTrEeBnKOAlvdt8Nh4BH3DhrmV3HVl+Ydc9V2G6iGZ6EmPxe3QG5dC9aYGollEXieasTFZm1Bt/LQMdyHmQEd+cmdIQNfGhxzz5pWpLP9g8LuoG+8h69TYaVFY2o0FjP2vSuPqGhMlXhcWgb/gJsiAOLGkS2ZdFbhpQg3kEyS5f/h91Wuoxy08JHpFxsvzWL3skfJ5eQc/BykvHyzzxzK\",\"ephemeralPublicKey\":\"BFnxpfpfIeFLmJ/KM/GcQyhU0MBlEReejnKa71gKFnV+5N2t3WNBnaaNu02gjy7Z5d07XO5+O77Qx3abHnw5rwk\\u003d\",\"tag\":\"kbnLkGZKyDKBWQAh6AyCNL55V4SF8DiZ4PeIudtKBH0\\u003d\"}"}
I need to json_decode it, do something with it then push it back. If I json_decode it, I will get the \u003d character decoded to =, which is fine. But how do I encode it back ? I think I played with every possible conversion function in PHP and I'm fresh out of ideas.
Here's a sandbox to play around with : http://sandbox.onlinephpfunctions.com/code/b93defec84a9a6f22f5085fbb7628b5afa816d95
In normal work you do not need to encode = to \u003d but if you must use somthing like this:
$encoded = str_replace('=','\\u003d', $encoded);
Note about your sandbox example:
In your example the token variable signedMessage is json in json
but after changes return as single json and not json in json like before changes.
maybe its fine for your application but check it
Related
I need to use a customer's API for loading JSON which only contains something like:
{"html" : "foo"}
The API is being used from other services so I'm pretty sure it's valid.
However, when trying to decode it using json_decode i'm always getting an empty string which means it's not valid. I found out i need to "fix" the JSON-String by replacing:
$json = str_replace("\\>", "\\\\>", $json); // \> = invalid json
It works mainly on each request but not on certain others but it's very tricky to debug and i can't imagine that replacing is the proper method.
How would i do it the easy way for converting the json string into a valid one?
thanks
Ok i could find out what's wrong:
The HTML contains backslashes in the closing tags, for example <br\>
You need to replace them like this:
$json = str_replace("\\>", "\\\\>", $json);
and json_decode will work
When users keep interacting with my web app, the pages keep doing calls so that some info can be stored in a cookie linked file that is stored on the server (with the PHP session file, it gets complex: I don't have choice to see a complete history, etc.)
So, anyway, with every ajax call, I create json_encoded data in a flat file with the unique cookie name.
Data example of one such cookie file: (keys/values may repeat)
{"name":"John Doe"}
{"email":"john#doe.com"}
{"location":"Disneyland, Orlando"}
{"country of residence":"Iceland"}
{"name":"Gill Bates"}
{"email":"Gill.Bates#sicromoft.com"}
Now, when I am searching this file, to retrieve data and to do other stuff, I would like to have the entire contents in one big array as if the entire data ws json_encoded in one shot.
How do I do this? I could do a bunch of str_replace and replace the "{" and "}" and get rid of the carriage returns but that seems to be a bit ugly
Is there a better way?
Thanks
I suggest to fix your json format by using str_replace as you saying because this is the only way to have a valid json format on using this function:
$str = '{"name":"John Doe"}
{"email":"john#doe.com"}
{"location":"Disneyland, Orlando"}
{"country of residence":"Iceland"}
{"name":"Gill Bates"}
{"email":"Gill.Bates#sicromoft.com"}';
$fix_json = "[" . str_replace("}\n{", "},{", $str) . "]";
and after this you can decode you json and convert it with json_decode, like this:
$dataArray = json_decode($fix_json, true);
My API URL Returned code in browser as shown below. but json_decode($api_url,true); returns null.
i checked json_last_error();, it returns 4(json error syntax).
it worked with json_decode(file_get_contents($api_url),true);
why it isn't work with json_decode. please help
{"dataset":{"id":27153572,"dataset_code":"20MICRONS_A_DEBT","database_code":"DEB","name":"20 Microns Limited,Total Debt","description":"\u003cp\u003e20 Microns Limited(NSE:20MICRONS)-Total Debt(Annual)\u003c/p\u003e","refreshed_at":"2018-09-21T08:04:08.278Z","newest_available_date":"2018-03-31","oldest_available_date":"2005-03-31","column_names":["PERIOD","STANDALONE","CONSOLIDATED"],"frequency":"annual","type":"Time Series","premium":true,"limit":null,"transform":null,"column_index":null,"start_date":"2005-03-31","end_date":"2018-03-31","data":[["2018-03-31",128.56,133.68],["2017-03-31",144.9,151.73],["2016-03-31",155.18,163.41],["2015-03-31",152.8,164.62],["2014-03-31",162.01,176.64],["2013-03-31",148.49,164.73],["2012-03-31",144.67,158.6],["2011-03-31",81.42,120.31],["2010-03-31",84.35,87.35],["2009-03-31",58.62,58.62],["2008-03-31",46.52,null],["2007-03-31",42.46,null],["2006-03-31",40.03,null],["2005-03-31",38.98,null]],"collapse":null,"order":null,"database_id":14992}}
What you are trying to do has no sense. $api_url is just an url so when you try to decode it then it doesn't have a json stucture and it will throw an exeption.
What you should decode is the data that this url returns to you.
So First you should get data from url then use json_decode($api_url,true);.
To get data you can use file_get_contents or curl.
Props to u_mulder who hit the nail on the head but I want to break this down for you a little.
Purpose of file_get_contents():
The file_get_contents() function is an inbuilt function in PHP which is used to read the contents of a file into a string.
Please note that the 'file' can be a file residing on your web server or a remote file (URL), which in essence will give you a web document back.
Purpose of json_decode():
The json_decode() function is an inbuilt function in PHP which is used to decode a JSON string. It converts a JSON encoded string into a PHP variable.
With that in mind you can see that performing json_decode on an invalid JSON string or a URL will render your result as NULL.
json_decode('https://www.website.com')
This is essentially what you are doing. performing the file_get_contents inside your json_decode first converts your URL/File ('https://www.website.com') into a string, that string then having JSON is then converted into an array by json_decode.
I'm very new to PHP but have a good understanding of C,
When I want to access some post data on an API i'm creating in PHP I use:
$_POST['date_set']
to fetch a value being passed for date - This all works perfectly, however I read I should be fetching it like this:
$date_set = trim(urldecode($_POST['date_set']));
This always returns a 00:00:00 value for the date after it's stored in my DB.
When I access directly using $_POST['date_set'] I get whatever value was posted, for example: 2013-08-28 10:31:03
Can someone tell me what I'm messing up?
You should try it like,
$date_set = $_POST['date_set'].explode(' ');//('2013-08-28 10:31:03').explode(' ')
echo $date_set[1];
or
echo date('H:i:s',strtotime($_POST['date_set'])));
//echo date('H:i:s',strtotime('2013-08-28 10:31:03'));
If you are very new in php the Read date()
You only run urldecode over data is URL encoded. PHP will have decoded it before populating $_POST, so you certainly shouldn't be using that. (You might have to if you are dealing with double-encoded data, but the right solution there should be to not double encode the data).
trim removes leading and trailing white-space. It is useful if you have a free form input in which rogue spaces might be typed. You will need to do further sanity checking afterwards.
urldecode — Decodes URL-encoded string
Description
string urldecode ( string $str )
Decodes any %## encoding in the given string. Plus symbols ('+') are decoded to a space character.
urldecode: is used only for GET requests. you should be fine using $_POST['date_set'] only.
http://php.net/manual/en/function.urldecode.php
You'd better do this way
if(isset($_POST['date_set'])){
$date_set = $_POST['date_set'];
}
then you can use $date_set how you want.
If you still get 00:00:00 for $date_set, the problem is coming from the code which provide you the $_POST value.
I'm writing PHP code that uses a database. To do so, I use an array as a hash-map.
Every time content is added or removed from my DB, I save it to file.
I'm forced by my DB structure to use this method and can't use mysql or any other standard DB (School project, so structure stays as is).
I built two functions:
function saveDB($db){
$json_db = json_encode($db);
file_put_contents("wordsDB.json", $json_db);
} // saveDB
function loadDB(){
$json_db = file_get_contents("wordsDB.json");
return json_decode($json_db, true);
} // loadDB
When echo-ing the string I get after the encoding or after loading from file, I get a valid json (Tested it on a json viewer) Whenever I try to decode the string using json_decode(), I get null (Tested it with var_dump()).
The json string itself is very long (~200,000 characters, and that's just for testing).
I tried the following:
Replacing single/double-quotes with double/single-quotes (Without any backslashes, with one backslash and three backslashes. And any combination I could think of with a different number of backslashes in the original and replaced string), both manually and using str_replace().
Adding quotes before and after the json string.
Changing the page's encoding.
Decoding without saving to file (Right after encoding).
Checked for slashes and backslashes. None to be found.
Tried addslashes().
Tried using various "Escape String" variants.
json_last_error() doesn't work. I get no error number (Get null, not 0).
It's not my server, so I'm not sure what PHP version is used, and I can't upgrade/downgrade/install anything.
I believe the size has something to do with it, because small strings seem to work fine.
Thanks Everybody :)
In your JSON file change null to "null" and it will solve the problem.
Check if your file is UTF8 encoded. json_decode works with UTF8 encoded data only.
EDIT:
After I saw uploaded JSON data, I did some digging and found that there are 'null' key. Search for:
"exceeding":{"S01E01.html":{"2217":1}},null:{"S01E01.html":
Change that null to be valid property name and json_decode will do the job.
I had a similar problem last week. my json was valid according to jsonlint.com.
My json string contained a # and a & and those two made json_decode fail and return null.
by using var_dump(json_decode($myvar)) which stops right where it fails I managed to figure out where the problem was coming from.
I suggest var_dumping and using find dunction to look for these king of characters.
Just on the off chance.. and more for anyone hitting this thread rather than the OP's issue...I missed the following, someone had htmlentities($json) way above me in the call stack. Just ensure you haven't been bitten by the same and check the html source.
Kickself #124