I want to remove all double quotes from a JSON file using PHP.
The following code outputs all the variables to a JSON file named example.json:
$var_geoJSON = 'var geoJSON = ';
file_put_contents('jsonfun.json', $var_geoJSON);
file_put_contents('jsonfun.json', json_encode($geojson, JSON_NUMERIC_CHECK), FILE_APPEND);
I was trying to get it to output something like this:
var geoJSON = {...}
Yet it outputs something like this:
"var geoJSON = " {...}
I am currently working with geoJSON to output to the open source leaflet.js mapping library, and the syntax requires that I have var geoJson = {...} instead of having "var geoJSON = "{...}.
I have tried using the PHP command preg_replace() replacing all the "" with spaces, yet that still didn't work and it outputted the same thing with the double quotes.
Any ideas?
Just use str_replace function http://www.w3schools.com/php/func_string_str_replace.asp example:
$result = str_replace('"', '', $json)
Related
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]
In PHP I'm trying to strip information and store them in $sysver variable from a string named $freply like this:
var id='E8ABFA19FDE2';
var sys_ver='17.37.2.49';
var app_ver='20.9.1.150';
using PHP sscanf with whe following parameters:
sscanf($freply, "var sys_ver='%[^']'", $sysver);
However a blank result in $sysver is all I get.
UPDATE
Working on the first row with:
sscanf($freply, "var id=' %[^']'", $ea);
Gives me a correct result loaded as expected in $ea, that shows E8ABFA19FDE2.
Someone is able to tell me where's the mistake?
Despite I'm using PHP I guess this question is related to Javascript too or any other C-like language.
What you're telling sscanf() is your string is formatted beginning with the literal characters var sys_ver... etc. then you're passing it a string that starts with var id... and it's NOPE'ing right out.
This works:
sscanf($freply, "var id='E8ABFA19FDE2';\nvar sys_ver='%[^']'", $sysver);
or this:
foreach (explode("\n", $freply) as $line) {
if (sscanf($line, "var sys_ver='%[^']'", $sysver)) break;
}
But really sscanf() is not quite the right tool for this job. Just use preg_match():
preg_match("/var sys_ver='([^']+)'/", $freply, $matches);
$sysver = $matches[1];
I have sth like that inside *.txt file.
function_name({"one": {"id": "id_for_one", "value": "value_for_one"}, ...});
And I am getting the file like this:
$source = 'FILE_NAME.txt';
$json = json_decode(file_get_contents($source),true);
echo $json['one']['value'];
It doesn't work, but when I remove function_name( and ); it works.
How to parse it without removing these strings?
You can't. It is not valid JSON with those. Take a substring that excludes them.
You will have to remove those strings. With the function_name portion it is not valid JSON.
A JSON string will typically either begin with { (object notation) or [ (array notation), but can also be scalar values such as a string or number. You cannot parse it without first making sure the string is valid JSON.
You are trying to get the string within a file and decoding it as a JSON file.
The 'function_name' isn't a valid JSON string, the rest inside yes.
How to parse it without removing these strings?
There is no way.
This should work for you.
$data = file_get_contents($source);
$data = substr($data, strlen("function_name("));
$data{strlen($data)-1}=$data{strlen($data)-2}=" ";
$json = json_decode($data,true);
Both {} and [] works for string to access individual characters.
The function in your text file, means that isn't a json file.
Remove the string using a regular expression, and your problem is fixed.
If the function is a fixed name, do something like this:
$source = 'FILE_NAME.txt';
$json_content = str_replace('function_name(', '', file_get_contents($source));
$json_content = substr($json_content,0,-2);
$json = json_decode($json_content,true);
echo $json['one']['value'];
I am trying to read a file as a string and return it to the client to be executed as javascript code in order to save it as a variable. Like so
<?php
$fileName = 'target.js';
$codeAsString = file_get_contents($fileName);
$script = 'var code=\'' . $codeAsString . '\'';
echo $script;
?>
Once returned, I want the variable code to have a string representation of the contents of target.js. However, it isn't working. I suspect it has to do with new line characters and single/double quotes... In Python they have a multi line quote
"""This
is
a "multi"
line
'quote'
"""
Is there anything like this in Javascript/php? I can't even wrap my head around whether I need the single quotes around $codeAsString when appending it to $script. Do I have to manually go in and prepend backslashes before all quotes, double quotes, back slashes...Surely they have helper functions for this
thanks.
json_encode is your friend...
<?php
$fileName = 'target.js';
$codeAsString = file_get_contents($fileName);
$script = 'var code= '.json_encode($codeAsString) .';';
echo $script;
?>
Use PHP function json_encode.
Is there a helper function that will properly escape a string to be rendered as a single quote quoted JavaScript string literal?
I know of jsQuoteEscape but it only handles quotes and does not treat \n & \r etc.
so if my string is 'line1\nlineb' (i.e. two lines with a newline between them)
and I use
var jsvar='<?php echo $this->helper('myextension')->jsQuoteEscape($mystring); ?>';
I will get in the rendered content
var jsvar='line1
line2';
which is a syntax error.
Thanks,
Eyal
Yes
$string = 'Hello
There';
var_dump( Mage::helper('core')->jsonEncode($string) );
var_dump( json_encode($string) );
I've never been clear if this encoding a non-object string datatypes as a javascript string is a side-effect of the JSON encoding, or if it's true, according to Hoyle Crockford JSON, so I always like to wrap my strings in an object when passing them around
$o = new stdClass();
$o->param = 'This is my
Param';
$json = json_encode($o);
echo 'var data = ' . $json . ';' . "\n";
echo 'var jsdata = data.param';
This is how you'd handle this with javascript. There's no method that's build specifically for this. If you're interested in seeing the helper methods you do have available from a block, checkout the methods in
app/code/core/Mage/Core/Block/Abstract.php
app/code/core/Mage/Core/Block/Template.php
and if you're dealing with a template that's part of a block higher up the chain, get its class and then check its definition
var_dump get_class($this);