开发者

When to use a list in JSON

开发者 https://www.devze.com 2023-01-31 10:47 出处:网络
I wrote a JSON compiler and decompiler in October. After running a bunch of tests against other people\'s JSON, I was satisfied that it worked, and moved on. I mostly focused on the compiler, because

I wrote a JSON compiler and decompiler in October. After running a bunch of tests against other people's JSON, I was satisfied that it worked, and moved on. I mostly focused on the compiler, because that's usually the hard part, trying to understand all the variables that people can throw at you. JSON was, as advertised, pretty easy to work with (though not as easy, imho, as it could have been). No matter.

Now we've got a format that's starting to gain traction, a JSONification of stream of news displayed by River2. A bunch of Javascript devs are working on renderings of this data, some of which are now already nicer than the one I use, but none are yet functional enough for me to switch to.

But there's a problem wi开发者_StackOverflow中文版th the JSON.

Each group of news bits is organized as a bunch of scalar data, like feed name, url, when the feed was last read, etc. Then there are one or more news items. If there's one item I just include a struct named item. If there's more than one I include a list of structs. The list is named item. I understood this is the convention for repeating elements in JSON.

http://scripting.com/images/2010/12/17/jsonShot.gif

In the screen shot above, there are two "updatedFeed" elements. The first has only one item, the second has more than one.

This causes problems for people in some languages because (apparently) it's hard for them to deal with an object without, in advance, knowing its type. So they say the solution is simple, always make it a list. Simple for them, but... :-)

But this is not so simple on my end. Because I'm using a generic JSON serializer, and it would have no way of knowing that "item" should always be a list. Unless...

One way of dealing with this (that I don't like and won't do) is to make everything a list.

I was just wondering what other JSON-producing environments do in situations like this.


JSON is a serialization format. It generally works best, if the same (expected) object has the same schema each time, or if the receiver is built to be flexible or ignore the parts that change.

In this case, it sounds to me that the news stream always should have the same format, so it sounds like you should tweak the object you are "compiling" to JSON, so that it always has the same structure, or use something like JSON Schema.

0

精彩评论

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