user1956641
user1956641

Reputation: 99

How can I convert json data?

I've got json data. There is "cyrillic" strings in json file, like this one:

\u0418\u0432\u0430\u043D\u043E\u0432 \u0418.

When I decode json and put this data in database table I get the string

Иванов И.

On one decoding web-site I entered this string and got very good (the one I need)

Иванов И.

And also this site told me that it was converted from CP1252 to UTF-8. So I tried to convert data from json after decoding manually using

mb_convert_encoding ( $string, "UTF-8","windows-1252");
mb_convert_encoding ( $string, "UTF-8","CP1252");

and

iconv("windows-1252","UTF-8",$string);
iconv("CP1252","UTF-8",$string);

Any of this functions made the string in database table look like

Øòðýþò ÃËœ.

or

Øòðýþò Ø.

both are not decoded on above site properly. So the question is, how do I convert this string?

Upd: used this sql request:

ALTER DATABASE logenterprise
    CHARACTER SET utf8

Tried after the same things that wrote above - result is the same. Also tried this just in case:

alter table mytable convert to CHARACTER SET utf8 COLLATE utf8_unicode_ci;

Upvotes: 3

Views: 542

Answers (1)

Alex B.
Alex B.

Reputation: 947

Curse you damned encodings ^^ They gave me a hard time too.

Everything looked fine (database, encoding of the inputdata and on the website), but still i got cryptic chars in my tables. So what's the problem then? It's the connection to your database-server.

Fortunately you can fix this with a simple query.

Right after establishing the mysql-connection you need to execute the following query:

mysql_query("SET NAMES 'utf8'");

Voilà. When you execute your INSERT-Query the data gets nicely saved in your db.

This saved my ass many times as i was handling 'Umlauts' and the €-sign.


Note: You shouldn't use mysql_xxx methods anymore as they are deprecated. I just used them in the example to make the code clearer.

Upvotes: 1

Related Questions