为什么 JSON 很重要?

发布于 2024-07-18 03:27:55 字数 198 浏览 7 评论 0原文

我最近才听说 JSON(Javascript 对象表示法)。 有人可以解释为什么它(被某些网站/博客/等)认为很重要吗? 我们已经有了 XML,为什么 JSON 更好(除了“原生于 Javascript”之外)?

编辑:嗯,主要答案主题似乎是“它更小”。 然而,它允许跨域获取数据这一事实对我来说似乎很重要。 或者这在实践中还没有被广泛使用?

I've only recently heard about JSON (Javascript Object Notation).
Can anybody explain why it is considered (by some websites/blogs/etc) to be important?
We already have XML, why is JSON better (apart from being 'native to Javascript')?

Edit: Hmm, the main answer theme seems to be 'it is smaller'. However, the fact that it allows data fetching across domains, seems important to me. Or is this in practice not (yet) much used?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(10

榆西 2024-07-25 03:27:56

XML 有几个缺点:

  • 它很重!
  • 它提供了内容的分层表示,与 Javascript 对象模型不完全相同(但非常相似)。
  • JavaScript 随处可用。 无需任何外部解析器,您可以直接使用 JS 解释器处理 JSON。

显然它并不是要完全取代 XML。 对于基于 JS 的 Web 应用程序,它的优点可能很有用。

XML has several drawbacks:

  • It's heavy!
  • It provides a hierarchical representation of content which is not exactly the same as (but pretty much similar to) Javascript object model.
  • Javascript is available everywhere. Without any external parsers, you can process JSONs directly with JS interpreter.

Clearly it's not meant to replace XML completely. For JS based Web apps, its advantages can be useful.

我的奇迹 2024-07-25 03:27:56

JSON 通常比其等效的 XML 小得多。 较小的传输意味着更快的传输,从而带来更好的用户体验。

JSON is generally much smaller than its XML equivalent. Smaller transfer means faster transfer, which results in a better user experience.

太傻旳人生 2024-07-25 03:27:56

JSON 之所以得到广泛使用,主要是因为它提供了一种规避 Web 浏览器中使用的同源策略并从而允许混搭的方法。

假设您正在域 A 上编写一个 Web 服务。您无法从域 B 加载 XML 数据并解析它,因为唯一的方法是 XMLHttpRequest,而 XMLHttpRequest 最初受到同源策略的限制。仅与包含页面位于同一域的 URL。

事实证明,由于各种原因,您可以请求

(作为练习留给读者的额外问题:为什么在没有服务器选择加入的情况下允许跨域使用

) 仅包含对象文字的内容是没有用的,因为如果不将值分配给某个变量,则无法对其执行任何操作。 因此,大多数服务使用 JSON 的变体,称为 JSONP (http ://bob.pythonmac.org/archives/2005/12/05/remote-json-jsonp/)。

随着混搭的流行,人们意识到 JSON 通常是一种方便的数据交换格式,特别是当 JavaScript 是渠道的一端时。 例如,JSON 在 Chromium 中被广泛使用,即使在双方都是 C++ 的情况下也是如此。 它只是一种很好的轻量级方式来表示简单数据,许多语言中都存在良好的解析器。

有趣的是,使用

JSON came into popular use primarily because it offers a way to circumvent the same-origin policy used in web browsers and thereby allow mashups.

Let's say you're writing a web service on domain A. You can't load XML data from domain B and parse it because the only way to do that would be XMLHttpRequest, and XMLHttpRequest was originally limited by the same-origin policy to talking to only URLs at the same domain as the containing page.

It turns out that for a variety of reasons, you are allowed to request <script> tags across origins. Clever people realized this was a good way to work around the limitation with XMLHttpRequest. Instead of the server returning XML, it can return a series of JavaScript object and array literals.

(bonus question left as an exercise to the reader: why is <script src="..."> allowed across domains without server opt-in but XHR isn't?)

Of course, returning a <script> which consists of nothing more than object literals is not useful because without assigning the values to some variable, you can't do anything with it. Thus, most services use a variant of JSON, called JSONP (http://bob.pythonmac.org/archives/2005/12/05/remote-json-jsonp/).

With the rise in popularity of mashups, people realized that JSON was a convenient data interchange format in general, especially when JavaScript is one end of the channel. For example, JSON is used extensively in Chromium, even in cases where C++ is on both sides. It's just a nice lightweight way to represent simple data, that good parsers exist for in many languages.

Amusingly, using <script> tags to do mashups is incredibly insecure because it is essentially XSS'ing yourself on purpose. So native JSON (http://ejohn.org/blog/native-json-support-is-required/) had to be introduced, which obviates the original benefits of the format. But by that time, it was already super popular :)

过度放纵 2024-07-25 03:27:56

JSON 更加简洁。 XML:

<person>
    <name>John Doe</name>
    <tags>
        <tag>friend</tag>
        <tag>male</tag>
   </tags>
</person>

JSON:

{"name": "John Doe", "tags": ["friend", "male"]}

重叠功能也更少。 例如,在 XML 中,选择使用元素(如上所述)与属性()之间存在着矛盾。

JSON is much more concise. XML:

<person>
    <name>John Doe</name>
    <tags>
        <tag>friend</tag>
        <tag>male</tag>
   </tags>
</person>

JSON:

{"name": "John Doe", "tags": ["friend", "male"]}

There's fewer overlapping features, too. For example, in XML there's tension between choosing to use elements (as above), versus attributes (<person name="John Doe">).

空城之時有危險 2024-07-25 03:27:56

如果您使用 Javascript,那么使用 JSON 会容易得多。 这是因为 JSON 可以直接计算为 Javascript 对象,这比 DOM 更容易使用。

借用并稍微改变上面的 XML 和 JSON

XML:

<person>
    <name>John Doe</name>
    <tag>friend</tag>
    <tag>male</tag>
</person>

JSON:

{ person: {"name": "John Doe", "tag": ["friend", "male"]} }

如果你想用 XML 获取第二个标签对象,你需要使用强大但冗长的 DOM api:

var tag2=xmlObj.getElementsByTagName("person")[0].getElementsByTagName("tag")[1];

而对于通过 JSON 传入的 Javascript 对象,你可以简单地使用:

var tag2=jsonObj.person.tag[1];

当然,Jquery 使 DOM 示例变得更加简单:

var tag2=$("person tag",xmlObj).get(1);

但是,JSON 只是“适合”Javascript 世界。 如果您使用它一段时间,您会发现与涉及基于 XML 的数据相比,您的精神负担要少得多。

上述所有示例都忽略了一个或多个节点可用、重复的可能性,或者该节点只有一个或没有子节点的可能性。 但是,为了说明 JSON 的本机性,要使用 jsonObj 执行此操作,您只需:(

var tag2=(jsonObj.person && jsonObj.person.tags && jsonObj.person.tags.sort && jsonObj.person.tags.length==2 ? jsonObj.person.tags[1] : null);

有些人可能不喜欢那么长的三元,但它可以工作)。 但 XML(在我看来)会更糟糕(我认为您不想采用三元方法,因为您会不断调用 dom 方法,这些方法可能需要根据实现重新完成工作):

var tag2=null;
var persons=xmlObj.getElementsByTagName("person");
if(persons.length==1) {
    var tags=persons[0].getElementsByTagName("tag");
    if(tags.length==2) { tag2=tags[1]; }
}

Jquery (未经测试):

var tag2=$("person:only-child tag:nth-child(1)",xmlObj).get(0);

If you are working in Javascript, it is much easier to us JSON. This is because JSON can be directly evaluated into a Javascript object, which is much easier to work with than the DOM.

Borrowing and slightly altering the XML and JSON from above

XML:

<person>
    <name>John Doe</name>
    <tag>friend</tag>
    <tag>male</tag>
</person>

JSON:

{ person: {"name": "John Doe", "tag": ["friend", "male"]} }

If you wanted to get the second tag object with XML, you'd need to use the powerful but verbose DOM apis:

var tag2=xmlObj.getElementsByTagName("person")[0].getElementsByTagName("tag")[1];

Whereas with a Javascript object that came in via JSON, you could simply use:

var tag2=jsonObj.person.tag[1];

Of course, Jquery makes the DOM example much simpler:

var tag2=$("person tag",xmlObj).get(1);

However, JSON just "fits" in a Javascript world. If you work with it for a while, you will find that you have much less mental overhead than involving XML based data.

All the above examples ignore the possibility that one or more nodes are available, duplicated, or the possibility that the node has just one or no children. However, to illustrate the native-ness of JSON, to do this with the jsonObj, you'd just have to:

var tag2=(jsonObj.person && jsonObj.person.tags && jsonObj.person.tags.sort && jsonObj.person.tags.length==2 ? jsonObj.person.tags[1] : null);

(some people might not like that long of ternary, but it works). But XML would be (in my opinion) nastier (I don't think you'd want to go the ternary approach because you'd keep calling the dom methods which may have to do the work over again depending on implementation):

var tag2=null;
var persons=xmlObj.getElementsByTagName("person");
if(persons.length==1) {
    var tags=persons[0].getElementsByTagName("tag");
    if(tags.length==2) { tag2=tags[1]; }
}

Jquery (untested):

var tag2=$("person:only-child tag:nth-child(1)",xmlObj).get(0);
抱着落日 2024-07-25 03:27:56

这取决于你要做什么。 这里有很多答案更喜欢 JSON 而不是 XML。 如果你深入观察的话,并没有太大的区别。

如果你有一个对象树,你只能得到 javascript 对象树。 如果你看看使用 OOP 风格访问的紧张感,你就会反感。 假设您有一个 A、B、C 类型的对象,它们是在树中构造的。 您可以轻松地将它们序列化为 JSON。 如果你读回它们,你只会得到一棵 javascript 对象树。 要重建 A、B、C,您必须手动将值填充到手动创建的对象中,或者进行一些修改。 听起来像是解析 XML 并创建对象吗? 嗯,是的:)

如今,只有最新的浏览器才提供对 JSON 的本机支持。 要支持更多浏览器,您有两种选择:a) 在 javascript 中加载 json 解析器来帮助您解析。 那么,这听起来有多胖呢? 我经常看到的另一个选项是 eval。 您只需对 JSON 字符串执行 eval() 即可获取对象。 但这引入了一系列全新的安全问题。 JSON 已指定,因此它不能包含函数。 如果您不检查对象的功能,有人可以轻松地向您发送正在执行的代码。

所以这可能取决于您更喜欢什么:JSON 还是 XML。 最大的区别可能是访问事物的方式,无论是脚本标签 XMLHTTPRequest...我将决定使用什么。 在我看来,如果浏览器对 XPATH 提供适当的支持,我通常会决定使用 XML。 但时尚是针对 json 并在 javascript 中加载额外的 json 解析器。

如果您无法决定,并且您知道您需要一些非常强大的东西,那么您可能需要看看 YAML。 阅读 YAML 非常有趣,可以更深入地了解该主题。 但这实际上取决于您想要做什么。

It depends on what you are going to do. There are a lot of answers here that prefer JSON over XML. If you take a deeper look there isn't a big difference.

If you have a tree of objects you get only tree of javascript objects back. If you take a look at the tension to use OOP style access than turns back on you. Assume you have an object of type A, B ,C that are constructed in a tree. You can easily enable them to be serialzed to JSON. If you read them back in you only get a tree of javascript objects. To reconstruct your A, B, C you have to stuff the values manually into manually created objects or you doing some hacks. Sound like parsing XML and creating objects? Well, yes :)

This days only the newest browsers come with native support for JSON. To support more browsers you have two options: a) you load a json paraser in javascript that helps you parsing. So, how fat does this sound regarding fatreeness? The other option as I often see is eval. You can just do eval() on a JSON String to get the objects. But that introduces a whole new set of security problems. JSON is specified so it can't contain functions. If you are not checking the objects for function someone can easily send you code that is being executed.

So it might depend on what you like more: JSON or XML. The biggest difference is propably the ways of accessing things, be it script tags XMLHTTPRequest... I would decide upon this what to use. In my opinion if there would be proper support for XPATH in the browsers I would often decide for XML to use. But the fashion is directed towards json and loading additional json parsers in javascript.

If you can't decide and you know you need something really powerful you ight have to take a look at YAML. Reading about YAML is very interesting to get more insight in the topic. But it really depends on what you are trying to do.

驱逐舰岛风号 2024-07-25 03:27:56

JSON 是一种在 Javascript 对象中序列化数据的方法。 语法取自该语言,因此处理 Javascript 的开发人员应该熟悉它,而且——作为对象的字符串化——它是一种比成熟的 XML 衍生品更自然的浏览器交互序列化方法(以及暗示的所有任意设计决策)。

它轻巧直观。

JSON is a way to serialize data in Javascript objects. The syntax is taken from the language, so it should be familiar to the developer dealing with Javascript, and -- being the stringification of an object -- it's a more-natural serialization method for interaction within the browser than a full-fledged XML derivative (with all the arbitrary design decisions that implies).

It's light and intuitive.

陌伤浅笑 2024-07-25 03:27:56

JSON 是一种基于文本的对象序列化格式,比 XML 更轻量级,并且直接与 JavaScript 的对象模型集成。 这就是它的大部分优点。

它的缺点(与 XML 相比)大致是:可用工具较少(忘记标准验证和/或转换,更不用说大多数编辑器中的语法突出显示或格式良好检查了),不太可能是人类可读的(有大量的JSON 和 XML 的可读性存在差异,因此这必然是一个模糊的陈述),与 JavaScript 的紧密集成使得与其他环境的集成不那么紧密。

JSON's a text-based object serialization format that's more lightweight than XML and that directly integrates with JavaScript's object model. That's most of its advantages right there.

Its disadvantages (compared to XML) are, roughly: fewer available tools (forget about standard validation and/or transformation, to say nothing of syntax highlighting or well-formedness checking in most editors), less likely to be human-readable (there's huge variations in the readability of both JSON and XML, so that's a necessarily fuzzy statement), tight integration with JavaScript makes for not-so-tight integration with other environments.

我一直都在从未离去 2024-07-25 03:27:56

并不是说它更好,而是它可以将许多东西捆绑在一起,以允许无缝数据传输,而无需手动解析!

例如 javascript -> C# 网络服务 -> javascript

It's not that it is better, but that it can tie many things together to allow seamless data transfer without manual parsing!

For example javascript -> C# web service -> javascript

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文