I have been stuck in this issue and cant seem to fix it.. I have this JSON STRING
$unBillableArr = ["{'id' : '123','to' : '+923412268656','MsgReceivedFrom' : '03349433314', 'message':'Qwertyy ', 'recdate':'2017-11-20 19:01:49'}"];
I need to convert it into array of object or maybe just one json object.. I have tried doing
json_decode($unBilledArr , true);
It gives me null.
Already tried these solutions as well
Convert a string to JSON object php
https://jonsuh.com/blog/convert-loop-through-json-php-javascript-arrays-objects/
I must be doing something wrong.. cant seem to figure out what..
P.s : This is the response i am getting and i can not do anything about the response.
You are trying to decode an array, either specify the specific item within the array, or make it a string.
For instance:
$unBillableArr = '{"id":"123", "to":"+923412268656", "MsgReceivedFrom":"03349433314", "message":"Qwertyy", "recdate":"2017-11-20 19:01:49"}';
$json = json_decode($unBillableArr, true);
// Or
$unBillableArr = ['{"id":"123", "to":"+923412268656", "MsgReceivedFrom":"03349433314", "message":"Qwertyy", "recdate":"2017-11-20 19:01:49"}'];
$json = json_decode($unBillableArr[0], true);
However, given the string you are receiving does not contain valid JSON and you are unable to control what you receive, I have prepared the following that will replace the single quotes in your JSON, and decode each item into an array:
$unBillableArr = ["{'id' : '123','to' : '+923412268656','MsgReceivedFrom' : '03349433314', 'message':'Qwertyy ', 'recdate':'2017-11-20 19:01:49'}"];
// Loop through each JSON string
$jsonObjects = []; // Change this name...
foreach ($unBillableArr as $jsonString) {
$jsonObjects[] = json_decode(str_replace("'", '"', $jsonString), true);
}
print_r($jsonObjects); // Proof it works
Please bear in mind that I would consider this to be a dirty fix. To fix this properly, you should go back to the source and ensure that the JSON they are returning to you is valid.
So I got a HTML page with a button. When I click the button, a separate javascript file sends a GET request to my PHP file, expecting a JSON object in return. My PHP reads a JSON formatted text file and should convert it into a JSONObject and echo it out for my javascipt. I had some code working before, but it doesn't seem to do it anymore since I changed to a Ajax aproach instead of having everything in the same file. This is my code:
readLog.php
<?php
class test{
function clean($string){
return json_decode(rtrim(trim($string),','),true);
}
function getLog(){
header('Content-Type: application/json');
$logLines = file('../../../home/shares/flower_hum/humid.log');
$entries = array_map("clean",$logLines);
$finalOutput = ['log' => $entries];
echo json_encode($logLines);
}
}
?>
My humid.log file looks like this:
{"date":"26/09/2016", "time":"22:40:46","temp":"16.0", "humidity":"71.0" }
{"date":"26/09/2016", "time":"23:10:47","temp":"16.0", "humidity":"71.0" }
Now If I press my button, this is the response I get checking the console in my web browser:
Response:
["{\"date\":\"26\/09\/2016\", \"time\":\"22:40:46\",\"temp\":\"16.0\", \"humidity\":\"71.0\" }{\"date\":\"26\/09\/2016\", \"time\":\"23:10:47\",\"temp\":\"16.0\", \"humidity\":\"71.0\" }\n"]
JSON:
"{"date":"26/09/2016", "time":"22:40:46","temp":"16.0", "humidity":"71.0" }{"date":"26/09/2016", "time":"23:10:47","temp":"16.0", "humidity":"71.0" }\n"
obviously something is wrong with the formatting, but I don't know what. As I said, this code worked just fine when I had my php and HTML in the same file.
EDIT:
I have also tried formatting the JSON with something like this, but it just prints the brackets:
function getLog(){
$text = file('../../../home/shares/flower_hum/humid.log');
$textRemoved ="["; //Add opening bracket.
$textRemoved .= substr($text, 0, strlen($text)-1); (Remove last comma)
$textRemoved .="]";//Add closing bracket
$json = json_encode($textRemoved);
echo $json;
}
So I managed to solve it myself. Basicly The formatting of the textfile was wrong and as some commentors said, I don't need to encode it if I am doing it myself. What I ended up doing was in my application that generates the log file to add comma after each row. Then in my PHP I added brackets and removed the last comma.
function getLog(){
header('Content-Type: application/json');
$file = file_get_contents('../../../home/shares/flower_hum/humid.log');
$lengthOfFile = strlen($file)-2;
$subFile = substr($file, 0, $lengthOfFile);
$res ="[";
$res .= $subFile;
$res .="]";
echo $res;
}
You can't just jam two+ JSON strings togther. It's JSON, which means it HAS to be syntactically correct Javascript CODE. If you want to join two json strings together, you HAVE to decode them to a native data structure, join those structures together, then re-encode the new merged structure:
$temp1 = json_decode('{"foo":"bar"}', true);
$temp2 = json_decode('{"baz":"qux"}', true);
$new = array_merge($temp1, $temp2);
echo json_encode($new);
which will produce:
{"foo":"bar","baz":"qux"}
and remain valid JSON/Javascript.
Why? Consider that bare integers are valid json:
json_encode(42) -> 42
json_encode(123) -> 123
If you have two json-encoded integers and jam together, you get a "new" integer:
42123
and on the receiving end, you'll be going "Ok, so where is the split between the two", because 4 and 2123 are just as valid as possible original values as 4212 and 3.
Sending the two integers as distinct and SEPARATABLE values would require an array:
[42,123]
I have a JSON Response like this:
{
"id":"2461",
"name":"GEORGIA INSTITUTE OF <leo_highlight style=border-bottom: 2px solid rgb(255, 255, 150); background-c",
"logo":"",
"address":null,
"city":null,
"state":null,
"campus_uri":"{{PATH}}2461\/"
},
....
....
When I do strip_tgs on this one, the whole JSON string is getting truncated at the name tag above. The JSON string looks like this.
{"id":"2461","name":"GEORGIA INSTITUTE OF
All below this line is gone. This is a huge JSON. But its getting truncated here.
Any ideas on what to do? I need to strip out all HTML tags.
Update:
Adding more details...
This JSON string I got is from encoding the query results array. So I get array from MySQL query and I encoded it with json_encode and trying to strip_tags on it.
$array = json_decode($json, true);
array_walk_recursive($array, function (&$val) { $val = strip_tags($val); });
$json = json_encode($json);
As simple... Decode it, walk through and encode it.
Strip out the tags after you have decoded the JSON object. You might do this in a lazy fashion (i.e. when needed) rather than go through every item an strip tags on all fields.
I am trying to create a report function for our firewall.
The firewall rules are stored in json format.
Here is a sample of the string.
[{"id":1,"enabled":true,"description":"TEMP","matchers":{"javaClass":"java.util.LinkedList","list":[{"invert":false,"javaClass":"com.untangle.node.firewall.FirewallRuleMatcher","value":"1.1.1.1","matcherType":"DST_ADDR"},{"invert":false,"javaClass":"com.untangle.node.firewall.FirewallRuleMatcher","value":"80","matcherType":"DST_PORT"},{"invert":false,"javaClass":"com.untangle.node.firewall.FirewallRuleMatcher","value":"1,3,2","matcherType":"DST_INTF"},{"invert":false,"javaClass":"com.untangle.node.firewall.FirewallRuleMatcher","value":"2.2.2.2","matcherType":"SRC_ADDR"},{"invert":false,"javaClass":"com.untangle.node.firewall.FirewallRuleMatcher","value":"1,2,wan","matcherType":"SRC_INTF"},{"invert":false,"javaClass":"com.untangle.node.firewall.FirewallRuleMatcher","value":"UDP,TCP,any","matcherType":"PROTOCOL"},{"invert":false,"javaClass":"com.untangle.node.firewall.FirewallRuleMatcher","value":"svrbjgu","matcherType":"DIRECTORY_CONNECTOR_USERNAME"},{"invert":false,"javaClass":"com.untangle.node.firewall.FirewallRuleMatcher","value":"intern-it","matcherType":"DIRECTORY_CONNECTOR_GROUP"}]},"ruleId":5001,"javaClass":"com.untangle.node.firewall.FirewallRule","block":false,"log":true}]
And the preg_match_all filter i have:
preg_match_all('/\"description":"(.*?)\","matchers"/',$str,$description);
preg_match_all('/\"id":(.*?)\,"/',$str,$id);
preg_match_all('/\"ruleId":(.*?)\,"/',$str,$rule_id);
preg_match_all('/\"enabled":(.*?)\,"description"/',$str,$enable);
preg_match_all('/\"block":(.*?)\,"/',$str,$block);
preg_match_all('/\"log":(.*?)\}/',$str,$log);
preg_match_all('/\"value":"(.*?)\","matcherType":"DST_ADDR"/',$str,$dest_add);
preg_match_all('/\"value":"(.*?)\","matcherType":"DST_PORT"/',$str,$dest_port);
preg_match_all('/\"value":"(.*?)\","matcherType":"DST_INTF"/',$str,$dest_int);
preg_match_all('/\"value":"(.*?)\,","matcherType":"SRC_ADDR"/',$str,$src_add);
preg_match_all('/\"value":"(.*?)\","matcherType":"SRC_INTF"/',$str,$src_int);
preg_match_all('/\"value":"(.*?)\","matcherType":"PROTOCOL"/',$str,$protocol);
preg_match_all('/\"value":"(.*?)\","matcherType":"DIRECTORY_CONNECTOR_USERNAME"/',$str,$user);
preg_match_all('/\"value":"(.*?)\","matcherType":"DIRECTORY_CONNECTOR_GROUP"/',$str,$group);
What happens is that the start for evry matcher is VALUE":" when i print $dest_port i get "1.1.1.1","matcherType":"DST_ADDR"},{"invert":false,"javaClass":"com.untangle.node.firewall.FirewallRuleMatcher","value":"80" instead of just 80.
Any one that have a preg_match_all to find the matchertype first and then read backwords to the "value":"?
Any help would be fantastic!
$xyz = <<<EOX
[{"id":1,"enabled":true,"description":"TEMP","matchers":{"javaClass":"java.util.LinkedList","list":[{"invert":false,"javaClass":"com.untangle.node.firewall.FirewallRuleMatcher","value":"1.1.1.1","matcherType":"DST_ADDR"},{"invert":false,"javaClass":"com.untangle.node.firewall.FirewallRuleMatcher","value":"80","matcherType":"DST_PORT"},{"invert":false,"javaClass":"com.untangle.node.firewall.FirewallRuleMatcher","value":"1,3,2","matcherType":"DST_INTF"},{"invert":false,"javaClass":"com.untangle.node.firewall.FirewallRuleMatcher","value":"2.2.2.2","matcherType":"SRC_ADDR"},{"invert":false,"javaClass":"com.untangle.node.firewall.FirewallRuleMatcher","value":"1,2,wan","matcherType":"SRC_INTF"},{"invert":false,"javaClass":"com.untangle.node.firewall.FirewallRuleMatcher","value":"UDP,TCP,any","matcherType":"PROTOCOL"},{"invert":false,"javaClass":"com.untangle.node.firewall.FirewallRuleMatcher","value":"svrbjgu","matcherType":"DIRECTORY_CONNECTOR_USERNAME"},{"invert":false,"javaClass":"com.untangle.node.firewall.FirewallRuleMatcher","value":"intern-it","matcherType":"DIRECTORY_CONNECTOR_GROUP"}]},"ruleId":5001,"javaClass":"com.untangle.node.firewall.FirewallRule","block":false,"log":true}]
EOX;
var_dump(json_decode($xyz)); //execute other operations, iteration etc here
This works much better than regex. Returns structured data, you can iterate through.
Ended up using with json_decode.
sample:
$jsondata ='[{"id":1,"enabled":true,"description":"TEMP","matchers":{"javaClass":"java.util.LinkedList","list":[{"invert":false,"javaClass":"com.untangle.node.firewall.FirewallRuleMatcher","value":"1.1.1.1","matcherType":"DST_ADDR"},{"invert":false,"javaClass":"com.untangle.node.firewall.FirewallRuleMatcher","value":"80","matcherType":"DST_PORT"},{"invert":false,"javaClass":"com.untangle.node.firewall.FirewallRuleMatcher","value":"1,3,2","matcherType":"DST_INTF"},{"invert":false,"javaClass":"com.untangle.node.firewall.FirewallRuleMatcher","value":"2.2.2.2","matcherType":"SRC_ADDR"},{"invert":false,"javaClass":"com.untangle.node.firewall.FirewallRuleMatcher","value":"1,2,wan","matcherType":"SRC_INTF"},{"invert":false,"javaClass":"com.untangle.node.firewall.FirewallRuleMatcher","value":"UDP,TCP,any","matcherType":"PROTOCOL"},{"invert":false,"javaClass":"com.untangle.node.firewall.FirewallRuleMatcher","value":"svrbjgu","matcherType":"DIRECTORY_CONNECTOR_USERNAME"},{"invert":false,"javaClass":"com.untangle.node.firewall.FirewallRuleMatcher","value":"intern-it","matcherType":"DIRECTORY_CONNECTOR_GROUP"}]},"ruleId":5001,"javaClass":"com.untangle.node.firewall.FirewallRule","block":false,"log":true}]';
$data = json_decode($jsondata,true);
echo '<table><tr><th WIDTH="10">Nr.</th><th WIDTH="10">RuleID</th><th WIDTH="150">Description</th><th WIDTH="100">Protocol</th><th WIDTH="75">Src Int</th><th WIDTH="150">Src Address</th><th WIDTH="100">Src Port</th><th WIDTH="75">Dest. Int</th><th WIDTH="150">Dest Address</th><th WIDTH="100">Dest. Port</th><th WIDTH="50">Action</th><th WIDTH="50">Log</th><th WIDTH="50">Enabled</th></tr>';
echo "<tr><td>test.</td><td> {$data[0]['ruleId']} </td><td>{$data[0]['description']}</td><td>{$data[0]['enabled']}</td></tr>" ;