Parsing JSON when fields are missing in some objects of an array

If you’ve ever encountered an array like this, where the edition is missing from the second book, you might have noticed that a normal JSON parse will only yield 1 value instead of 2 (of which the second is empty).

{
   "book":[
      {
         "id":"444",
         "language":"C",
         "edition":"First",
         "author":"Dennis Ritchie "
      },
      {
         "id":"555",
         "language":"C++",
         "author":" Bjarne Stroustrup "
      }
   ]
}  

This might cause you some trouble when trying to merge multiple lists later on, as they will have a different number of items. So I made a small script to show you an alternative way of doing this.

You basically want to parse every single object of the array, then perform a FOREACH loop and parse the values of each object, and finally add the formatted string to a master list.

Here’s the LoliCode

BLOCK:ConstantString
  value = "{\"book\":[{\"id\":\"444\",\"language\":\"C\",\"edition\":\"First\",\"author\":\"Dennis Ritchie \"},{\"id\":\"555\",\"language\":\"C++\",\"author\":\" Bjarne Stroustrup \"}]}"
  => VAR @json
ENDBLOCK

BLOCK:Parse
  input = @json
  jToken = "book[*]"
  RECURSIVE
  MODE:Json
  => VAR @books
ENDBLOCK

BLOCK:ConstantList
  value = []
  => CAP @output
ENDBLOCK

FOREACH book IN books
BLOCK:Parse
  input = @book
  jToken = "id"
  MODE:Json
  => VAR @id
ENDBLOCK

BLOCK:Parse
  input = @book
  jToken = "language"
  MODE:Json
  => VAR @language
ENDBLOCK

BLOCK:Parse
  input = @book
  jToken = "edition"
  MODE:Json
  => VAR @edition
ENDBLOCK

BLOCK:AddToList
  list = @output
  item = $"id: <id>, language: <language>, edition: <edition>"
ENDBLOCK
END

Ruri

4 Likes