i am trying to parse json its working in online website but not working on json_decode() php, below is my json.
{"category":"group_channel:message_send","sender":{"nickname":"Four Six","user_id":"917777770046","profile_url":"https:\/\/sendbird.com\/main\/img\/profiles\/profile_05_512px.png","metadata":{}},"custom_type":"application\/octet-stream","mention_type":"users","mentioned_users":[],"app_id":"C14BC2EA-ED60-4A82-9441-5C312A6EA991","members":[{"is_blocking_sender":false,"unread_message_count":1,"total_unread_message_count":1,"is_active":true,"is_online":true,"is_hidden":0,"channel_mention_count":0,"nickname":"Four Six","is_blocked_by_sender":false,"user_id":"917777770046","channel_unread_message_count":0,"state":"joined","push_enabled":true,"push_trigger_option":true,"profile_url":"https:\/\/sendbird.com\/main\/img\/profiles\/profile_05_512px.png","metadata":{}}],"type":"MESG","payload":{"custom_type":"application\/octet-stream","created_at":1570690168039,"translations":{},"message":"H4sIAAAAAAAAALWTXYucMBSG\/4rkWockRh3nrrNlYViYFpbSyyUmx5mwmkiMpXaZ\/94T54MpC6Ut\nVASPb3Ke85W8kR7GUR5gp8mGCOCUFm2V6aIpMqHKOpOqEVnRasYbJbhqZFbqNeNFVWdlK1QmqoZm\nUqO+VrpSDLgStCApab3rEVmzankoFSWqYR4A1UvQl9b5HlV1lOGPE8D9g5w7J9HhjSyEy\/eMoAx3\njAEGsmEpAW0CWNl0Mew++nYyPC5ORFrtndEofgM\/GmdRi87KWfQJEYu0FYuGlkHGb+8a08F+6hvw\n78trjR\/DXvYx2KObPEqdvCnP5jsK0EvT4R+aUmuPnUDuKSUHsHphLunLMI1nGyPDp3ZrfDiehcG7\nFnP4bFSYPHzxF1g\/72zroo2w3mnTGtDb+X2S17UPWCErKlrWlDG65hX6xXr5fb0xOiI4ZXXGKL7\/\nSl9f6Pk9\/dYA8pTltUiTbefUa\/KUJs9H+Tr5YfLJg+ucne+UNPkI3dGkCXJpjk47q41cWo0x+XpV\n1oyWeY6CPZBNVa2YKHLBKpysCTHlvcNmJl9hDGfUMvPJBh8Xr7Q4g1j6dccPM8TzscRclj1AeLGX\n0V6Tu2\/PLy2oc178rnOn6Pif7qIZH1w\/dBAgkmfy9xMsebpcsdvBZ5jw6SfcNiZDPgQAAA==\n","data":"message_form","message_id":2839079954},"channel":{"is_distinct":false,"name":"KPGI Workday","custom_type":"kpgi_workday_data","is_ephemeral":false,"channel_url":"sendbird_group_channel_150279781_505f37b8b653c01febe37245d447f7098d0fe53c","is_public":false,"is_super":false,"data":"{\"chatApp\":\"sendbird\",\"chatId\":\"4e2005f7-d5b5-4c69-acb4-5fd12bc42cba\",\"topParentId\":\"4e2005f7-d5b5-4c69-acb4-5fd12bc42cba\",\"formNumber\":\"0\",\"creatorName\":\"Four Six\",\"creatorId\":\"917777770046\",\"topic\":\"KPGI Workday\",\"formstatus\":\"{\\\"kpgi_workday_travel_form\\\":0,\\\"kpgi_workday_initiate_break\\\":0,\\\"kpgi_workday_travel\\\":0,\\\"kpgi_workday_expense\\\":0,\\\"kpgi_workday_close_data\\\":0,\\\"kpgi_workday_timesheet\\\":0}\",\"type\":\"kpgi_workday_data\",\"parentId\":\"\"}","is_discoverable":false},"sdk":"Android"}
Please try this JSON:
{"category":"group_channel:message_send","sender":{"nickname":"Four Six","user_id":"917777770046","profile_url":"https://sendbird.com/main/img/profiles/profile_05_512px.png","metadata":{}},"custom_type":"application/octet-stream","mention_type":"users","mentioned_users":[],"app_id":"C14BC2EA-ED60-4A82-9441-5C312A6EA991","members":[{"is_blocking_sender":false,"unread_message_count":1,"total_unread_message_count":1,"is_active":true,"is_online":true,"is_hidden":0,"channel_mention_count":0,"nickname":"Four Six","is_blocked_by_sender":false,"user_id":"917777770046","channel_unread_message_count":0,"state":"joined","push_enabled":true,"push_trigger_option":true,"profile_url":"https://sendbird.com/main/img/profiles/profile_05_512px.png","metadata":{}}],"type":"MESG","payload":{"custom_type":"application/octet-stream","created_at":1570690168039,"translations":{},"message":"H4sIAAAAAAAAALWTXYucMBSG/4rkWockRh3nrrNlYViYFpbSyyUmx5mwmkiMpXaZ/94T54MpC6Ut\nVASPb3Ke85W8kR7GUR5gp8mGCOCUFm2V6aIpMqHKOpOqEVnRasYbJbhqZFbqNeNFVWdlK1QmqoZm\nUqO+VrpSDLgStCApab3rEVmzankoFSWqYR4A1UvQl9b5HlV1lOGPE8D9g5w7J9HhjSyEy/eMoAx3\njAEGsmEpAW0CWNl0Mew++nYyPC5ORFrtndEofgM/GmdRi87KWfQJEYu0FYuGlkHGb+8a08F+6hvw\n78trjR/DXvYx2KObPEqdvCnP5jsK0EvT4R+aUmuPnUDuKSUHsHphLunLMI1nGyPDp3ZrfDiehcG7\nFnP4bFSYPHzxF1g/72zroo2w3mnTGtDb+X2S17UPWCErKlrWlDG65hX6xXr5fb0xOiI4ZXXGKL7/\nSl9f6Pk9/dYA8pTltUiTbefUa/KUJs9H+Tr5YfLJg+ucne+UNPkI3dGkCXJpjk47q41cWo0x+XpV\n1oyWeY6CPZBNVa2YKHLBKpysCTHlvcNmJl9hDGfUMvPJBh8Xr7Q4g1j6dccPM8TzscRclj1AeLGX\n0V6Tu2/PLy2oc178rnOn6Pif7qIZH1w/dBAgkmfy9xMsebpcsdvBZ5jw6SfcNiZDPgQAAA==\n","data":"message_form","message_id":2839079954},"channel":{"is_distinct":false,"name":"KPGI Workday","custom_type":"kpgi_workday_data","is_ephemeral":false,"channel_url":"sendbird_group_channel_150279781_505f37b8b653c01febe37245d447f7098d0fe53c","is_public":false,"is_super":false,"data":"{\"chatApp\":\"sendbird\",\"chatId\":\"4e2005f7-d5b5-4c69-acb4-5fd12bc42cba\",\"topParentId\":\"4e2005f7-d5b5-4c69-acb4-5fd12bc42cba\",\"formNumber\":\"0\",\"creatorName\":\"Four Six\",\"creatorId\":\"917777770046\",\"topic\":\"KPGI Workday\",\"formstatus\":\"{\"kpgi_workday_travel_form\":0,\"kpgi_workday_initiate_break\":0,\"kpgi_workday_travel\":0,\"kpgi_workday_expense\":0,\"kpgi_workday_close_data\":0,\"kpgi_workday_timesheet\":0}\",\"type\":\"kpgi_workday_data\",\"parentId\":\"\"}","is_discoverable":false},"sdk":"Android"}
I have made some edits. If this works, you can do a string compare to see the differences, but overall, I just deleted some extra slashes.
Related
I am having a weird issue, when i use json_decode() on some json from a jquery ajax call it's coming back always saying that the json is malformed (JSON_ERROR_SYNTAX).
I say this is weird because if i take a copy of the raw posted json from the developer console and manually push it through json_decode() then it decodes perfectly fine.
I have uploaded a txt file of the example json here : https://drive.google.com/file/d/1IZ5RkpFK7KLUNYeZe4dPdxGWZXinmFSJ/view?usp=sharing which works manually parsing it but not from posted data. Another weird issue is if i save the json string to a longtext field in a mysql database and then pull it out again, it then decodes fine; but this isn't ideal, it needs to validate it before going to the database and i'm unsure why this would allow it to decode anyway.
Any ideas?
This might be happeing due to new line code added in your code. You can add below code and try to decode the code again it might work.
$content = preg_replace('/[\r\n\t\s]+/s', ' ', $content);#new lines, multiple spaces/tabs/newlines
$content = preg_replace('#/\*.*?\*/#', '', $content);#comments
$content = preg_replace('/^\s+/', '', $content);#spaces on the begining
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 want to parse this I tried almost everything but I couldn't understand this , I m getting this from WordPress database table wp_postmeta.
Tried - unserialize , serialize, json_encode
string(303) "s:294:"a:1:{i:2364;a:1:{s:9:"schedules";a:1:{s:13:"578db85b83681";a:5:{s:13:"minutes_start";s:3:"540";s:11:"minutes_end";s:4:"1020";s:5:"weeks";a:6:{i:0;s:2:"on";i:1;s:2:"on";i:2;s:2:"on";i:3;s:2:"on";i:4;s:2:"on";i:6;s:2:"on";}s:10:"date_start";s:10:"07/18/2016";s:8:"date_end";s:10:"09/30/2016";}}}}";"
Try unserialize(). This worked.
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
For some reason json_decode is returning NULL with valid JSON.
The json is located here: http://www.nfl.com/liveupdate/scorestrip/scorestrip.json
I am getting the file contents of the page (file_get_contents) and then running json_decode on it.
Also tried stripslashes b/c of magic quotes.
Thanks in advance,
Phil
$json = file_get_contents('http://www.nfl.com/liveupdate/scorestrip/scorestrip.json');
var_dump(json_decode($json));
The empty array elements are invalid JSON, ie the multiple commas with no values between
["Thu","7:30","Final",,"BAL","6","PHI","13",,,"55424",,"PRE1","2011"]
^ Here ^ Here ^Here
You could try inserting empty strings between multiple commas (thanks hakre), ie
$json = preg_replace('/,(?=,)/m', ',""', $json);
// I'm dubious about this working, don't have PHP to test but it works in JS
I don't know if this messes up your ability to continue using the data though
I came the same conclusion as Phil, but it took me about 5 minutes longer. : )
However, I noticed a problem in his output... it is dropping a field.
I don't like doing this kind of pattern detection in RegEx, only because I think it is harder to maintain. In this case, I just run it through a while loop.
while (strpos($json,',,'))
{
$json = str_replace(',,',',"",', $json);
}
I'm sure Phil can come up with a proper RegEx, but this solution will maintain the right # of entries & their ordinal positions.
For anyone looking in 2014. The new feed data link should be:
http://www.nfl.com/liveupdate/scores/scores.json