Peter Rehm's Blog

apple,development,life & more

Escape special characters within JSON.stringify

Mit 2 Kommentaren

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.

Geschrieben von Peter Rehm

07.10.2014 um 19:11:34

Abgelegt in Programmierung

Tags für diesen Artikel: ,

Symfony2 Render String with Twig

Ohne Kommentare

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'));

Geschrieben von Peter Rehm

26.05.2014 um 13:32:35

Tags für diesen Artikel: , ,

Remote notes to git commits

Ohne Kommentare

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.

Geschrieben von Peter Rehm

30.01.2014 um 09:23:25

Tags für diesen Artikel: ,

wkhtmltopdf and fonts on a linux/debian server

Ohne Kommentare

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

Geschrieben von Peter Rehm

14.09.2013 um 16:20:33

Tags für diesen Artikel: , ,

Setting secure file permissions for PHP projects

Ohne Kommentare

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 {} \;

Geschrieben von Peter Rehm

23.07.2013 um 08:21:45

PHP 5.5 Opcache in Development

Ohne Kommentare

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.

Geschrieben von Peter Rehm

14.07.2013 um 12:36:34

Tags für diesen Artikel: ,

Google Maps API in Twitter Bootstrap Tabs

Ohne Kommentare

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!

Geschrieben von Peter Rehm

22.01.2013 um 18:40:21

Tags für diesen Artikel: , ,

git; insufficient permission

Ohne Kommentare

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

Geschrieben von Peter Rehm

08.01.2013 um 10:32:56

Tags für diesen Artikel:

Changing Locale on Debian to English

Ohne Kommentare

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)

Geschrieben von Peter Rehm

06.01.2013 um 22:54:51

Tags für diesen Artikel: , ,

Installing MongoDB Binaries on Mac

Ohne Kommentare

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'

Geschrieben von Peter Rehm

05.11.2012 um 14:49:57

Tags für diesen Artikel: , ,

Symfony2 Ordered Fixtures

Ohne Kommentare

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.

Geschrieben von Peter Rehm

17.10.2012 um 19:33:40

Tags für diesen Artikel: ,

Symfony2 Permissions on Mac

Ohne Kommentare

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

Geschrieben von Peter Rehm

17.10.2012 um 19:31:39

Tags für diesen Artikel: ,

Compare Content of 2 Folders

Ohne Kommentare

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".

Geschrieben von Peter Rehm

25.08.2012 um 12:29:32

Tags für diesen Artikel:

Compiling error regarding xcode select

Ohne Kommentare

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...

Geschrieben von Peter Rehm

18.08.2012 um 17:03:38

Tags für diesen Artikel: ,

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

Ohne Kommentare

Link to a nice installer of the latest PHP version.

Geschrieben von Peter Rehm

07.08.2012 um 12:27:50