JSON 对应于具有属性的 XML?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4056419/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JSON corresponding to an XML with attributes?
提问by dan
I am designing an API for my webapp.
我正在为我的 webapp 设计一个 API。
I was thinking to support only JSON responses (not XML) because more streamlined.
我想只支持 JSON 响应(而不是 XML),因为更精简。
But I have just bumped to this XML:
但我刚刚遇到了这个 XML:
<folders>
<folder id="123" private="0" archived="0" order="1">Shopping</folder>
</folders>
and I was wondering how the corresponding JSON would be. I have the feeling, in this case, XML would be more compact.
我想知道相应的 JSON 会如何。我有一种感觉,在这种情况下,XML 会更紧凑。
Thanks, Dan
谢谢,丹
采纳答案by dan
Perhaps:
也许:
{
"folders": [
{ "id":123, "private":0, "archived":0, "order":1, "title":"Shopping" },
...
]
}
Because there is notan exact correspondence between XML and JSON, you are free (e.g. have to define) how the two data-structures map. For instance, in the above, the "folder" element is implicit in the nested objects in the "folders" array.
因为XML 和 JSON 之间没有确切的对应关系,所以您可以自由地(例如必须定义)这两个数据结构如何映射。例如,在上面,“文件夹”元素隐含在“文件夹”数组中的嵌套对象中。
This could be expanded as in:
这可以扩展为:
"folders": [{"folder": { .... }]
Etc, but there is still the problem of not being able to capture content+attributesas consistently as XML. In any case, your data-structure -> JSON|XML serializer likely works in a particular way (and please, please, use a library, not "hand-rolled" JSON-string-munging). That is; the format of the XML and JSON should be uniformly dictated (somehow) by the data-structure for transmission.
等等,但仍然存在无法像 XML 那样一致地捕获内容+属性的问题。在任何情况下,您的数据结构 -> JSON|XML 序列化程序可能以特定方式工作(并且请使用库,而不是“手工制作的” JSON-string-munging)。那是; XML 和 JSON 的格式应该由传输的数据结构统一规定(以某种方式)。
回答by Supervision
This approach supports inverse transformation to XML:
这种方法支持对 XML 的逆向转换:
{
"folders": {
"folder":{
"@": {
"id": "123",
"private": "0",
"archived": "0",
"order": "1"
},
"#": "Shopping"
}
}
}
It works correctly with js2xmlparser.
它与js2xmlparser一起正常工作。
回答by underscore
There is a JSON notation / convention called badgerfishattempts to standardizes (at least its own terms) the way of preserving of most of the low level XML semantics when XML DOM represented as JSON DOM (with attributes of course) (see http://badgerfish.ning.com/).
当 XML DOM 表示为 JSON DOM(当然有属性)时,有一个名为badgerfish的 JSON 符号/约定试图标准化(至少它自己的术语)保留大多数低级 XML 语义的方式(参见http:// badgerfish.ning.com/)。
So you can easily convert back the badgerfishied-jsonrepresentation to the XML representation and you still work on the structure with your favorite XML toolset (for me its XPATH / QUERY expressions and tools).
因此,您可以轻松地将badgerfishied-json表示转换回XML 表示,并且您仍然可以使用您最喜欢的 XML 工具集(对我来说是 XPATH / QUERY 表达式和工具)处理结构。
It has also easy to memorize syntax rules (total 9) like: "Attributes go in properties whose names begin with @". You can work on badgerfishied-jsonin the text editor without overloading your neural circuitry unnecessarily. Usually you can memorize them in the first pass.
它也很容易记住语法规则(共 9 条),例如:“属性进入名称以 @ 开头的属性”。您可以在文本编辑器中处理badgerfishied-json,而不会不必要地超载您的神经回路。通常你可以在第一遍记住它们。
回答by spier
An example of how YQL presents XML and the corresponding JSON. No need to know anything about YQL to understand this but if you are interested your can check the YQL console and try it out yourself in the YQL console
YQL 如何呈现 XML 和相应 JSON 的示例。无需了解 YQL 即可理解这一点,但如果您有兴趣,可以查看 YQL 控制台并在YQL 控制台中亲自尝试
XML
XML
<results>
<a href="/">NBA</a>
<a class="topnav" href="#">TEAMS</a>
<a href="/teams/">Teams</a>
<a href="/hawks/">Atlanta</a>
JSON
JSON
"results": {
"a": [
{
"href": "/",
"content": "NBA"
},
{
"class": "topnav",
"href": "#",
"content": "TEAMS"
},
{
"href": "/teams/",
"content": "Teams"
},
{
"href": "/hawks/",
"content": "Atlanta"
},
回答by Roman Goyenko
Could be compact in the JSON too, attribute is just the same as the value inside tag
也可以在 JSON 中压缩,属性与标签内的值相同
from here:
从这里:
http://www.json.org/example.html
http://www.json.org/example.html
{"widget": {
"debug": "on",
"window": {
"title": "Sample Konfabulator Widget",
"name": "main_window",
"width": 500,
"height": 500
},
"image": {
"src": "Images/Sun.png",
"name": "sun1",
"hOffset": 250,
"vOffset": 250,
"alignment": "center"
}
}}
The same text expressed as XML:
以 XML 表示的相同文本:
<widget>
<debug>on</debug>
<window title="Sample Konfabulator Widget">
<name>main_window</name>
<width>500</width>
<height>500</height>
</window>
<image src="Images/Sun.png" name="sun1">
<hOffset>250</hOffset>
<vOffset>250</vOffset>
<alignment>center</alignment>
</image>
</widget>
回答by Aram Gharib
It seems to me that the most exact correspondence between XML and JSON would need to represent an XML node as a triplet (i.e. array): [name, attributes, value], with name being a string, attributes an object with attribute names as keys and attribute values as (string) values, and value a string (for atomic values) or an array of such triplets.
在我看来,XML 和 JSON 之间最准确的对应关系需要将 XML 节点表示为一个三元组(即数组):[名称、属性、值],名称为字符串,属性为以属性名称为键的对象和属性值作为(字符串)值,并将字符串值(对于原子值)或此类三元组的数组。
By such mapping the JSON-equivalent of
通过这样的映射 JSON 等价物
<folders>
<folder id="123" private="0" archived="0" order="1">Shopping</folder>
</folders>
would be
将是
[ "folders",
{},
[
[ "folder",
{ "id": "123",
"private": "0",
"archived": "0",
"order": "1"
},
"Shopping"
]
]
]
Actually the idea behind this mapping is that:
实际上,这种映射背后的想法是:
1) XML-JSON transformation be reversible. 2) The "sibling" relationship of sub-nodes be preserved
1) XML-JSON 转换是可逆的。2)保留子节点的“兄弟”关系
At the same time the distinction between attribute nodes and value nodes is explicit here.
同时,属性节点和值节点之间的区别在这里是明确的。
Does it make sense? And does it justify the complexity overhead?
是否有意义?它是否证明了复杂性开销的合理性?
回答by realbart
edit
编辑
A similar method is advocated on http://www.jsonml.org/. They coined the term json markup language.
http://www.jsonml.org/上提倡使用类似的方法。他们创造了术语 json 标记语言。
You can pick any mapping you like, but if you map
你可以选择任何你喜欢的映射,但是如果你映射
<el attr="value">
txt
</el>
to
到
{"el":{"attr":"value","content":"txt"}}
then how would you map:
那么你将如何映射:
<el attr="value" content="txt1">txt2</el>
I'd make use of the fact that some attibute names are forbidden.
我会利用一些属性名称被禁止的事实。
{"el":{"attr":"value", "content":"txt1", "":["txt"]}
Or a more compex example:
或者更复杂的例子:
<widget>
<debug>on</debug>
<window title="Sample Konfabulator Widget">
I just put some text here
<name>main_window</name>
<width>500</width>
<height>500</height>
</window>
<image src="Images/Sun.png" name="sun1">
<hOffset>250<unit>mm</unit></hOffset>
<vOffset>250</vOffset>
<alignment>center</alignment>
</image>
</widget>
could map to:
可以映射到:
{"widget":{"":[
{"debug":{"":["on"]}},
{"window":{"title":"Sample Konfabulator Widget", "": [
"I just put some text here",
{"name":{"":["main window"]}},
{"width":{"":["500"]}},
{"height":{"":["500"]}}
]},
{"image":{"src":"Images/Sun.png", "name":"sun1", "":[
{"hOffset":{"":["250",{"unit":{"":["mm"]}}]}},
{"vOffset":{"":["250"]}},
{"alignment":{"":["center"]}}
}
]}
The rules for this conversion are unambiguous:
这种转换的规则是明确的:
- an element is converted to an object.
- The object key is the element name.
- The object value is an object itself, with:
- an attibute is mapped to an object property. (key/value)
- the object content is mapped to a special property.
- The special property name is an empty string. This can never collide with an xml attribyte name.
- The special property value is an array.
- Within the array, plain text is represented as a string.
- Within the array, elements are represented as objects, as described above.
- 一个元素被转换为一个对象。
- 对象键是元素名称。
- 对象值是一个对象本身,具有:
- 一个属性被映射到一个对象属性。(核心价值)
- 对象内容被映射到一个特殊的属性。
- 特殊属性名称是一个空字符串。这永远不会与 xml 属性名称发生冲突。
- 特殊属性值是一个数组。
- 在数组中,纯文本表示为字符串。
- 在数组中,元素表示为对象,如上所述。
To safe space, there is a way to unambigously simplify mentioned mapping:
为了安全空间,有一种方法可以明确地简化提到的映射:
{"widget":{"":[
{"debug":"on"},
{"window":{"title":"Sample Konfabulator Widget", "": [
"I just put some text here",
{"name":"main window"},
{"width":"500"},
{"height":"500"}
]},
{"image":{"src":"Images/Sun.png", "name":"sun1", "":[
{"hOffset":["250",{"unit":"mm"}]},
{"vOffset":"250"},
{"alignment":"center"}
}
]}
If an element doesn't have any attibutes, the value object (containing the special empty string mapping to an array) is replaced by the array directly. So instead of:
{"hOffset":{"":["250",{"unit":{"":["mm"]}}]}}
如果元素没有任何属性,值对象(包含映射到数组的特殊空字符串)将直接替换为数组。所以而不是:
{"hOffset":{"":["250",{"unit":{"":["mm"]}}]}}
you get
你得到
{"hOffset":["250",{"unit":["mm"]}]}
If the element content is just text, the array containing the string value is replaced by the string value directly, so you get:
{"hOffset":["250",{"unit":"mm"}]}
如果元素内容只是文本,则将包含字符串值的数组直接替换为字符串值,因此得到:
{"hOffset":["250",{"unit":"mm"}]}
This way, there will always be exactly one way to map the jml (json markup language) back to xml (or html)
这样,总是只有一种方法可以将 jml(json 标记语言)映射回 xml(或 html)
回答by FlyingSheep
Opening caveat:In this answer I am deliberately standing back from the original question, and expanding the scope somewhat. Sometimes to ask the question behind the question we need to look at the big picture first.
开场警告:在这个答案中,我特意回避了最初的问题,并稍微扩大了范围。有时要问问题背后的问题,我们需要先看大局。
Just as all animals are equal, all translations from JSON to XML, and from XML to JSON are unequal. There can be no mathematically correct answers to this question, and even if there are, they may be wrong. All answers will be a matter of opinion, and depend on the exact use-case(s).
正如所有动物都是平等的一样,所有从 JSON 到 XML 以及从 XML 到 JSON 的翻译都是不平等的。这个问题在数学上不可能有正确的答案,即使有,也可能是错误的。所有答案都将取决于意见,并取决于确切的用例。
JSON and XML both support and omit concepts that make perfect, reversible and native translations difficult.
JSON 和 XML 都支持和省略使完美、可逆和本地翻译变得困难的概念。
To name just some:
仅举几例:
XML requires a root element. JSON does not.
XML distinguishes between Elements and Attributes. Attributes are leaves, Elements maybe leaves or branches. JSON objects are close to Elements, but have no direct equivalent to Attributes.
JSON has arrays; the nearest XML equivalent is a parent Element, but some translations fall foul where there is only one child element.
XML has namespaces….. The less said about those the better…
JSON is intended to be compact and lightweight, and is closer (in my humble opinion) to YAML than XML.
XML 需要一个根元素。JSON 没有。
XML 区分元素和属性。属性是叶子,元素可能是叶子或树枝。JSON 对象接近于元素,但没有直接等同于属性。
JSON 有数组;最接近的 XML 等效项是父元素,但有些翻译在只有一个子元素的情况下会出错。
XML 有命名空间..... 越少越好...
JSON 旨在紧凑和轻量级,并且比 XML 更接近(在我看来)YAML。
Where a concept exists in the source language, but not in the target language, we need to be inventive and creative in our translation. Your use-cases are key.
如果某个概念存在于源语言中,但不存在于目标语言中,则我们需要在翻译中发挥创造力。您的用例是关键。
e.g.
例如
Should the result be as native as possible in the target language? Would we model it like this in JSON? Would we model it like this in XML?
Should the result be reversible to the original source, even at the expense of “native feel”?
Is compactness a criteria? This can be a case for JSON over an element-heavy XML, but not for JSON translated from XML and designed to be translated back.
结果是否应该尽可能以目标语言为母语?我们会在 JSON 中像这样建模吗?我们会在 XML 中像这样建模吗?
结果是否应该可逆到原始来源,即使以“原生感觉”为代价?
紧凑性是标准吗?这可能是基于元素密集型 XML 的 JSON 的情况,但不适用于从 XML 翻译并设计为被翻译回来的 JSON。
To make a comparison with human languages: In Swiss German we love our diminutives: Nouns are routinely reduced to the small form where this would be strange in English; but even more bizarrly, we have diminutives of verbs!
与人类语言进行比较:在瑞士德语中,我们喜欢我们的小词:名词通常被简化为小形式,这在英语中会很奇怪;但更奇怪的是,我们有动词的缩写!
So: “wir machen es k?chele”, might translate technically to “we will cook littely”, or “we do a little cooking” but either would be poor and incorrect english, and somehow miss the idea.
所以:“wir machen es k?chele”,在技术上可能翻译成“我们会做一点点”,或者“我们做一点点菜”,但要么是差劲的英语,要么是不正确的英语,不知何故错过了这个想法。
“we will do a spot of cooking” or “we will have some fun cooking” would be much closer to the original idea. But I suspect that Anthea Bell (of Asterix-to-english translation fame) would truly get the point; “let's cook a feast….”
“我们会做一个地方做饭”或“我们会有一些有趣的烹饪”会更接近最初的想法。但我怀疑 Anthea Bell(以 Asterix 到英语的翻译成名)会真正明白这一点;“我们做个饭吧……”
Back to the original question. Python programmers have a concept of pythonesque: = most fitting to the core ethos of python. The answer by user166390 (the accepted answer at the time of this answer) strikes me as the most JSONesque.
回到最初的问题。Python程序员有一个pythonesque的概念:=最符合python的核心精神。user166390 的答案(在此答案中接受的答案)让我觉得是最 JSONesque。
回答by óscar Gómez Alca?iz
My choice for XML representation, to make sure it's somehowreversible, is as follows (using your example):
我对 XML 表示的选择,以确保它在某种程度上是可逆的,如下(使用您的示例):
<folders>
<folder id="123" private="0" archived="0" order="1">Shopping</folder>
</folders>
translates to:
翻译成:
{
"folders": [
{
"folder": [
{
"@id": 123,
"@private": 0,
"@archived": 0,
"@order": 1,
"$t": "Shopping"
}
]
}
]
}
So by using @as an indicator for "attribute" and $tas indicator for "text content" I can revert the JSON string to a faithful version of the original XML.
因此,通过@用作“属性”的$t指示符和“文本内容”的指示符,我可以将 JSON 字符串还原为原始 XML 的忠实版本。
A nice Node package to perform this conversion is XML2JSON, although it doesn't do anything special with the attributes, and some extra code is required to produce this output.
执行这种转换的一个很好的 Node 包是XML2JSON,尽管它对属性没有做任何特殊的事情,并且需要一些额外的代码来产生这个输出。
回答by Adam Byrtek
JSON is more uniform than XML and doesn't distinguish between plain-text attributes and hierarchical contents. The natural representation for your example would be
JSON 比 XML 更统一,并且不区分纯文本属性和分层内容。您的示例的自然表示将是
[
{"id": 123, "private": 0, "archived": 0, "order": 1, "name": "Shopping"}
]
This is still more compact than the respective XML.
这仍然比各自的 XML 更紧凑。

