0

I'm receiving a JSON array over web sockets, and I have a buffer which is built up, currently I'm assuming that I'll receive the complete JSON array, with nested JSON objects and arrays. But I know from experience that often these strings can be broken up. So I need to check for a valid JSON array before I should try to process the text. Obviously due to the nested arrays, I can't just check for the presence of an opening and a closing square bracket.

I'm using libcereal to parse the JSON, but I can't see anything in the documents to suggest that it can do this. What would people suggest would be the simplest thing? A C++11 regex for JSON?

Alex
  • 669
  • 15
  • 37
  • 1
    One thing is that you *should* write unit tests for `libcereal` to determine its behaviour when faced with invalid `json`. The other is to have some sort of guarantee that the string you end up with is definitely valid `json` or you know it is not. One thing that springs to mind is for the source to add a fixed sized crc at the front of the string. – quamrana Jul 30 '20 at 20:12
  • Unfortunately, I'm implementing JSON to a specification, so I can't alter the form of the JSON. The other comms protocols I've used have done just that (although CRC at the end of the string). – Alex Jul 30 '20 at 20:15
  • You can still use the first and last character as a form of check. If you can determine that `libcereal` has defined behaviour when parsing invalid `json`, then you can also avoid the parse if you have neither: `"{ ... }"` nor `"[ ... ]"`. – quamrana Jul 30 '20 at 20:18
  • Yes, but I want to account for potentially nested arrays, so just checking for a closing square bracket wouldn't quite cut it. I think I'm going to end up writing a JSON validator using regular a regular expression. – Alex Jul 30 '20 at 21:06
  • Why write a validator when libcereal should do it for you? Plus I meant that, for a long string, a parser might take a long time to give you an answer (especially if you ask each time another string fragment arrives), but you don’t need to ask if the last character doesn’t ‘match’ the first. – quamrana Jul 30 '20 at 21:14
  • I'm parsing one of the objects contained within the JSON array using cereal. Unfortunately, it's not possible to get cereal to work with the entire format of JSON that I'm expecting, because that object may change. – Alex Jul 31 '20 at 11:36

0 Answers0