开发者

Is use of @attributes in JSON non-standard or standard?

We're adding JSON output to an existing API that outputs XML, to make MobileHTML integration much easier. However, our developer has queried the use of @attributes appearing in the JSON output.

Our original XML looks like:

<markers>
    <marker id="11906" latitude="52.226578"
    ...

and so the JSON comes out as:

callbackname({"marker":[{"@attributes":{"id":"11906","latitude":"52.226578"
....

Our developer has stated:

"Although '@attributes' is legal JSON, it seems to break dot notation, so I can't call data.@attributes. I can call data['@attributes'], so there's a workaround, but it seems safer just to avoid the @-symbol, unless there's a good reason for it."

The XML->JSON(P) conversion is done using:

$xmlObject = simplexml_load_string ($data);
$data = json_encode ($xmlObject);

I want to make our API as easy-to-integrate as possible, and ther开发者_如何学编程efore to use standard stuff where possible. But we're using the native PHP json_encode function, so I'd be surprised if it's doing something non-standard.

Is use of @attributes non-standard? Is this basically just the problem that our API is a bit broken in terms of using <marker id..> rather than <marker><id> ?


The JSON standard only specifies what is and isn't valid; it doesn't set convention. There's nothing inherently wrong with using property names which aren't valid Javascript identifiers.

However, as your developer points out, this does make it slightly more awkward to use the result in JS, as it makes it impossible to use dot notation. On the gripping hand, using attributes for simple content is usually seen as "good XML" and you're using using default, built-in tools to convert from XML to JSON. I'd tend to consider that a good enough reason to leave it as it is.

If it were me, I'd look at how difficult it would be to implement a custom XML -> JSON converter. If it's simple and straightforward, go that route and avoid @attribute (it will also likely make your JSON smaller and simpler). If it's too much hassle, however, missing out on dot notation isn't the end of the world. At worst, var attr = data.marker["@attributes"]; will get around the issue.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜