I have some json I need to decode, alter and then encode without messing up any characters.

If I have a unicode character in a json string it will not decode. I'm not sure why since json.org says a string can contain: any-Unicode-character- except-"-or-\-or- control-character. But it doesn't work in python either.

{"Tag":"Odómetro"}

I can use utf8_encode which will allow the string to be decoded with json_decode, however the character gets mangled into something else. This is the result from a print_r of the result array. Two characters.

[Tag] => Odómetro

当我再次编码数组时,字符转义为ascii,根据json规范,这是正确的:

"Tag"=>"Od\u00f3metro"

有什么办法可以让我逃脱吗?json_encode没有提供这样的选项,utf8_encode似乎也不起作用.

Edit我看到json_encode有一个unscaped_unicode选项.然而,它并没有像预期的那样工作.哦,该死,它只在PHP5.4上.我将不得不使用一些正则表达式,因为我只有5.3.

$json = json_encode($array, JSON_UNESCAPED_UNICODE);
Warning: json_encode() expects parameter 2 to be long, string ...

推荐答案

从你所说的一切来看,你正在处理的原始Odómetro字符串似乎是用ISO 8859-1编码的,而不是UTF-8.

以下是我这么认为的原因:

  • json_encode produced parseable output after you ran the input string through utf8_encode, which converts from ISO 8859-1 to UTF-8.
  • 您确实说过,在执行utf8_encode之后使用print_r时,您得到了"损坏"的输出,但您得到的损坏输出实际上正是try 将UTF-8文本解析为ISO 8859-1时会发生的情况(UTF-8中的ó是\x63\xb3,但ISO 8859-1中的顺序是ó).
  • 你的htmlentities%迂回解决方案奏效了.htmlentities需要知道输入字符串的编码方式才能正常工作.如果不指定,则假定为ISO 8859-1.(令人困惑的是,html_entity_decode默认为UTF-8,因此您的方法具有从ISO 8859-1转换为UTF-8的效果.)
  • 你说你在Python中也遇到了同样的问题,这似乎排除了PHP的问题.

PHP will use the \uXXXX escaping, but as you noted, this is valid JSON.

So, it seems like you need to configure your connection to Postgres so that it will give you UTF-8 strings. The PHP manual indicates you'd do this by appending options='--client_encoding=UTF8' to the connection string. There's also the possibility that the data currently stored in the database is in the wrong encoding. (You could simply use utf8_encode, but this will only support characters that are part of ISO 8859-1).

最后,正如另一个答案所指出的,您确实需要确保使用HTTP头或其他方式声明正确的字符集(当然,这个特定问题可能只是您进行print_r次测试的环境的产物).

Json相关问答推荐

使用Powershell脚本将配置信息块添加到json文件

无法根据vega规范中的条件设置文本 colored颜色

如何获取brew list作为JSON输出

从先前的REST调用创建动态JSON主体

时间序列的Vega Lite分组条形图

在Golang中从 struct 手动创建JSON对象

当列为空时从 SQL 获取 JSON

JOLT 转换仅过滤一个字段

JSONPath:查找子项目条件在字符串列表中的项目

在Flutter 中将 map 的 Json 转换为 list

如何在生产环境中更改 Flutter 应用程序中的数据模型?

使用 Javascript 判断 JSON 对象是否包含值

如何使用法语口音对数组进行 json_encode?

可以通过 POST 使用 EventSource 传递参数的服务器发送事件 (SSE)

Rails:format.js 或 format.json,或两者兼而有之?

在 Qt 4.7 中解析 JSON 的最简单方法

jQuery JSON 响应总是触发 ParseError

如何使用 Jackson 注释从 HttpResponse 反序列化 JSON 对象?

带有方法参数的 WCF webHttpBinding 错误. 最多可以在没有包装元素的情况下序列化一个主体参数

使用 Retrofit 解析动态密钥 Json 字符串