views:

47

answers:

2

I am planning a protocol where two applications open a socket between them and send and receive legal json objects.

Can a sequence of json objects be unequivocally parsed, or will I need delimiters, or prefixing each object with its lengths or something like that?

+2  A: 

Real JSON objects always start and end with matching { and } characters. So you should be able to build a stream parser that correctly determines the boundaries on the fly, without needing to know the lengths in advance.

See json.org for details of the syntax.

Avi
True. Additionally legal JSON values also include arrays, which are enclosed in [ ] (legal json values are Objects and Arrays).
StaxMan
+1  A: 

Valid JSON objects have balanced delimiters.

Can you be 100% sure that you will only receive valid objects? Can you have network glitches? What about if the sender dies in mid transmission? I think you'll need either:

a). Some agreement about the JSON objects you're receiving so that you can ignore a partial stream until you see the start of one of your agreed payloads. Eg. everything is an "Envelope" object

b). a stack-like recovery mechanims pushing and "popping" counting opening and closing delimiters until you are sure you have the beginning of a new record. With sufficiently pathalogical corruption this sounds hard to do reliably.

I very much prefer the first option.

djna