我正在创建一个复杂的JavaScript库,用于使用我公司的服务器端框架.

服务器端框架将其数据编码为简单的XML格式.没有花哨的名称空间或类似的东西.

Ideally I'd like to parse all of the data in the browser as JSON. However, if I do this I need to rewrite some of the server side code to also spit out JSON. This is a pain because we have public APIs that I can't easily change.

What I'm really concerned about here is performance in the browser of parsing JSON versus XML. Is there really a big difference to be concerned about? Or should I exclusively go for JSON? Does anyone have any experience or benchmarks in the performance difference between the two?

I realize that most modern web developers would probably opt for JSON and I can see why. However, I really am just interested in performance. If there's a proven massive difference then I'm prepared to spend the extra effort in generating JSON server side for the client.

推荐答案

JSON should be faster since it's JS Object Notation, which means it can be recognized natively by JavaScript. In PHP on the GET side of things, I will often do something like this:

<script type="text/javascript">
    var data = <?php json_encode($data)?>;
</script>

For more information on this, see here:

Why is Everyone Choosing JSON Over XML for jQuery?

而且在"生成"JSON时,您真正需要付出什么"额外的努力"?当然,你不能说你将手动构建JSON字符串?几乎所有现代服务器端语言都有将本机变量转换为JSON字符串的库.例如,PHP的core json_encode函数可以转换如下关联数组:

$data = array('test'=>'val', 'foo'=>'bar');

into

{"test": "val", "foo": "bar"}

Which is simply a JavaScript object (since there are no associative arrays (strictly speaking) in JS).

Json相关问答推荐

Jolt Change将对象添加到数组

如何将自定义卡保存到dart/flutter中的共享偏好设置?

从Razor Pages的AJAX Json呈现DataTables问题.Net GET

对面的行/列进行排序时可能出现错误

在Ansible中从json中提取特定数据

在Zig中解析JSON失败

如何避免解析 ISuperObject 类型字段中的 json 对象

将=分隔值文件转换为:json文件

jq 中的整个单词匹配

如何使用 serde_json 构建有状态的流式解析器?

无法在 json --data 中使用变量

如何判断字符串是否为json格式

如何在golang中获取 struct 的json字段名称?

从 Postgres 中的 json 对象中提取键、值

如何使用 C# 将 JSON 文本转换为对象

Jackson 没有使用 @JsonProperty 覆盖 Getter

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

通过 JSON 发送 HTML 代码

如何从 MySQL 中检索 JSON 数据?

在播放框架 JsObject 中解析 Json 数组