简体   繁体   中英

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 therefore 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM