Peter Rehm's Blog

apple,development,life & more

Escape special characters within JSON.stringify

with 2 Comments

In order to stringify an Object to a JSON string you have to escape the special characters.
Specials characters are for example the following:

\b  Backspace (ascii code 08)
\f  Form feed (ascii code 0C)
\n  New line
\r  Carriage return
\v  Vertical tab
'  Apostrophe or single quote
"  Double quote
\  Backslash caracter
& Ampersand

Unfortunately JSON.stringify() is not taking care of the special characters. However you can
easily convert those characters with a replacer function within JSON.stringify().

The method to handle such characters looks as follows:


// escape json strings
function escapeSpecialCharacters(string)
return string
.replace(/[']/g, "\\'")
.replace(/["]/g, '\\"')
.replace(/[&]/g, "\\&")
.replace(/[\n]/g, "\\n")
.replace(/[\r]/g, "\\r")
.replace(/[\t]/g, "\\t")
.replace(/[\b]/g, "\\b")
.replace(/[\v]/g, "\\v")
.replace(/[\f]/g, "\\f");

// replacer handler for JSON stringify
function stringifyReplacer(key, value)
if (typeof value === 'string') {
return escapeSpecialCharacters(value);

return value;

Now you only have to pass the function name "stringifyReplacer" to the stringify Method.

var object = { 'asd' : 'as\nd' };
var json = JSON.stringify(object, stringifyReplacer);

Now you should have an valid JSON string which you can parse again with JSON.parse().

Always escaping whenever you stringify a object to JSON is a good idea to keep you application
working even when special characters are being provided.

Posted by Peter Rehm

10/07/2014 at 07:11:34 PM

Posted in Programmierung

Defined tags for this entry: ,

Symfony2 Render String with Twig

without Comments

At some point you might find the need to render templates from an string rather
than an actual file. This is needed for dynamic templates.

This is not possible with the default Symfony2 configuration, however it is easy to
adjust the configuration.

I ended up adding the Twig_Loader_String to the Loader chain with teh following
service configuration:

        class: Twig_Loader_String
            - { name: twig.loader }

With having this small snippet in the service.yml of one of your bundles you can
render strings with the normal twig instance from the DI container.

    $renderedString = $this->get('twig')->render('Hello my name is {{ name }}!', array($name => 'Peter'));

Posted by Peter Rehm

05/26/2014 at 01:32:35 PM

Defined tags for this entry: , ,

Remote notes to git commits

without Comments

Wit git notes you have an easy option of adding notes to commits. This is e.g. useful to
attach the github discussion to a commit.

Unfortunately the workflow to achieve this is slightly more complicated than just adding
commits. You can get your stuff done with the following commands.

git remote update 
git checkout <sha>
git notes --ref=github-comments add -m <content> <sha>
git push <remote> refs/notes/github-comments

I recommend to have a different refs for different notes types to not have any conflicts.

You can read more about git notes here.

Posted by Peter Rehm

01/30/2014 at 09:23:25 AM

Defined tags for this entry: ,

wkhtmltopdf and fonts on a linux/debian server

without Comments

I just wondered why the created pdf is different between the one I had in my dev environment
and the one in production. The actual reason has been missing fonts in this case.

You can easily install the most common windows and mac fonts on your debian server:

apt-get install msttcorefonts
tar xzvf ttf-mac-fonts.tar.gz
sudo mv ttf-mac-fonts /usr/share/fonts/
sudo fc-cache -f -v

Posted by Peter Rehm

09/14/2013 at 04:20:33 PM

Defined tags for this entry: , ,

Setting secure file permissions for PHP projects

without Comments

I am setting the permission for folders to 755 and for files to 644.
This can be adjusted automatically with find:

$ find /path/to/project -type d -exec chmod 755 {} \;
$ find /path/to/project -type f -exec chmod 644 {} \;

Posted by Peter Rehm

07/23/2013 at 08:21:45 AM

PHP 5.5 Opcache in Development

without Comments

PHP 5.5 comes with the Zend Opcache built in. There are also recommended
settings for production which needs to be adjusted for development.

In development you usually dont want to wait until you see your latest changes.
Therefore you need to set the revalidate_freq to 0 in order to revalidate the
files on each request. My development configuration looks like following:


To manually clear the opcache just execute the following in your command

php -r 'opcache_reset();'

NOTE: In case you are going to use Zend OPcache together with Xdebug,
be sure that Xdebug is loaded after OPcache. "php -v" must show Xdebug
after OPcache.

Posted by Peter Rehm

07/14/2013 at 12:36:34 PM

Defined tags for this entry: ,

Google Maps API in Twitter Bootstrap Tabs

without Comments

It is a common request to use the Google Maps API in some a tab.
I came across the issue again today using Twitter Bootstrap. If you
embed the MapCanvas not on the first tab you will notice that the
Map will not be fully loaded...

The issue can be solved with calling
    google.maps.event.trigger(map, 'resize');

once the tab on which the map is included is activated.

If you have the following tabs (Example using an tabbed form)
<ul class="nav nav-tabs">
    <li class="active"><a href="#tab-first" data-toggle="tab"><i class="icon-tasks"></i> Todo</a></li>
    <li><a href="#tab-second" data-toggle="tab"><i class="icofont-leaf"></i> My fancy Map</a></li>

<form action="#" method="post" class="form-horizontal tab-content well">
    <fieldset id="tab-first" class="tab-pane active">
        <h2>Form elements to be added here...</h2>
    <fieldset id="tab-second" class="tab-pane">
        <div id="mapCanvas" class="span6 pull-right"></div>
        <h2>Fancy Map</h2>

you can handle the resize with the following JavaScript Snippet.

    <script type="text/javascript">
        // handler to resize map once the tab content is shown to fix
        // loading and display of the google maps canvas
        $('a[data-toggle="tab"]').on('shown', function (e) {

            // only resize if the tab which contains the map has been shown
            if($('href') == '#tab-second') {
                google.maps.event.trigger(map, 'resize');

I hope this helps you!

Posted by Peter Rehm

01/22/2013 at 06:40:21 PM

Defined tags for this entry: , ,

git; insufficient permission

without Comments

If you get the following error

error: insufficient permission for adding an object to repository database .git/objects
fatal: failed to write object
fatal: unpack-objects failed

you have messed up something with the permissions. In this case you have to ensure,
that the permissions of the .git file get fixed.

chown -R .git

Posted by Peter Rehm

01/08/2013 at 10:32:56 AM

Defined tags for this entry:

Changing Locale on Debian to English

without Comments

If you want to change the locale on your Debian system you can make
this habben with the following two commands:

dpkg-reconfigure locales

After that you have to restart your console (type the name of your console or
open up a new terminal)

Posted by Peter Rehm

01/06/2013 at 10:54:51 PM

Defined tags for this entry: , ,

Installing MongoDB Binaries on Mac

without Comments

Get latest binaries from here:
and unzip.

sudo mv mongodb-osx-x86_64-2.2.1 /usr/local/mongodb
sudo mkdir /usr/local/mongodb_data /var/log/mongodb
sudo chown -R root /usr/local/mongodb
sudo vi /usr/local/mongodb/mongod.conf

Insert the following content

# Store data alongside MongoDB instead of the default, /data/db/
dbpath = /usr/local/mongodb_data
# Only accept local connections
bind_ip =

Create a LaunchDaemon

sudo vi /Library/LaunchDaemons/org.mongodb.mongod.plist

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN"
<plist version="1.0">

sudo launchctl load /Library/LaunchDaemons/org.mongodb.mongod.plist

Try it with http://localhost:28017

sudo sh -c 'echo "/usr/local/mongodb/bin" > /etc/paths.d/mongodb'

Posted by Peter Rehm

11/05/2012 at 02:49:57 PM

Defined tags for this entry: , ,

Symfony2 Ordered Fixtures

without Comments

If you want to set the order in which the Fixtures are boing loaded there are
two steps:

- Use the AbstractFixture Interface

class LoadCompanyData extends AbstractFixture implements OrderedFixtureInterface

- Add getOrder Methode

public function getOrder()
    return 1;

Than it will work.

Posted by Peter Rehm

10/17/2012 at 07:33:40 PM

Defined tags for this entry: ,

Symfony2 Permissions on Mac

without Comments

To configure the permissions on mac use the following commands:

sudo rm -rf app/cache/
sudo rm -rf app/logs/

sudo chmod +a "_www allow delete,write,append,file_inherit,directory_inherit" app/cache app/logs
sudo chmod +a "yourusername allow delete,write,append,file_inherit,directory_inherit" app/cache app/logs

Posted by Peter Rehm

10/17/2012 at 07:31:39 PM

Defined tags for this entry: ,

Compare Content of 2 Folders

without Comments

If you need to compare 2 folders on a windows machine to figure out
whether the content matches to check e.g. if you have really copied
all files you can do this on the command line.

- open cmd
- cd folder1
- dir /S /b > content_folder1.txt
- cd folder 2
- dir /S /b > content_folder1.txt
- fc content_folder1.txt content_folder1.txt

Hint: You can also pipe the output of fc by adding "> diff.txt".

Posted by Peter Rehm

08/25/2012 at 12:29:32 PM

Defined tags for this entry:

Compiling error regarding xcode select

without Comments

If you get this error

xcode-select: Error: No Xcode is selected. Use xcode-select -switch <path-to-xcode>, or see the xcode-select manpage (man xcode-select) for further information.

Make sure that you have the Apple Command Line Tools from installed. This should be necessary unless you want to develop OSX or iOS applications.

Then just execute this on the command line to set the default entry.

sudo xcode-select -switch /usr/bin

There you go...

Posted by Peter Rehm

08/18/2012 at 05:03:38 PM

Defined tags for this entry: ,

PHP 5.4.x on Mac OSX 10.6,10.7 or 10.8

without Comments

Link to a nice installer of the latest PHP version.

Posted by Peter Rehm

08/07/2012 at 12:27:50 PM