Best way to construct a one, two level json Object?

Hi!

Can anyone suggest an easy way to construct a JSON object that’s one level deep or two… ??

I think a Library would be an overkill for this app. I want to send multiple values in one event in JSON representation inside the DATA payload of the event.

I am planning on using String formatting… But wanted to know if someone has a better idea…

Any recommendations welcomed.

Let’s use an example.

You want your Photon to send events that have definite start (t0) and end (t1) times. So you decide to make (1) a “timestamp” object that stores those two parameters, and (2) an event type label. That’s a two-level JSON object, because the timestamp is an object itself. Let’s say one of your events is like, motion being detected in a room or something. Your JSON could look like:

{
  "eventType": "roomMotion",
  "timestamp": {
    "t0":  123819841,
    "t1":  123824789
  }
}

So when you send this from the Photon, just send an escaped string!!

// C++ (Photon)
  String msg = "{\"eventType\": \"roomMotion\", \"timestamp\": { \"t0\":  123819841, \"t1\":  123824789 } }";
  Spark.publish("roomEvent", msg, 60, PRIVATE);

When you receive the event in the server, you can parse the payload back into a JSON object in the JavaScript:

  // JavaScript (Server)
  Spark.onEvent("roomEvent", function(event) {
    var eventObject = JSON.parse( event.data );
    console.dir( eventObject );
  });

That’s how I do it, that’s how America does it, and it’s worked out pretty well so far.

1 Like

Awesome!

Thanks!