A common way to handle this is to persist the data to a file or an external database, and then have a later process (either another channel or a Scheduled Script) iterate through the persisted data and build the JSON.
Another way is to use a Script Variable, with the scope set to Channel. You can use a Scheduled Script that runs before the channel starts to initialze it as a JSON object, and then your code can take the data from each incoming message and add it to your JSON array. NOTE that Script Variables with their scope set to Channel are NOT thread safe, so you will want to make sure your channel is set to process one message at a time (see this KB about concurrency) so that only one process is updating the Script Variable at a time.