1

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?

flybywire
  • 261,858
  • 191
  • 397
  • 503

2 Answers2

2

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
  • 19,934
  • 4
  • 57
  • 70
  • True. Additionally legal JSON values also include arrays, which are enclosed in [ ] (legal json values are Objects and Arrays). – StaxMan Jul 14 '09 at 19:03
0

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
  • 54,992
  • 14
  • 74
  • 117