Skip to content

Adding keys to object in a loop #84

@SeanDS

Description

@SeanDS

I am having trouble adding keys to a JsonObject within a loop:

#include <ArduinoJson.h>

// output pins
unsigned int outputPins[8] = {2, 3, 5, 6, 7, 8, 9, 11};

// number of defined pins in list
const int NUMBER_OF_OUTPUTS = (sizeof(outputPins) / sizeof(int));

void setup()
{
  // open serial communications and wait for port to open:
  Serial.begin(9600);

  StaticJsonBuffer<1024> jsonBuffer;

  JsonObject& root = jsonBuffer.createObject();

  for (int i = 0; i < NUMBER_OF_OUTPUTS; i++) {   
    String key = String("pin_") + String(i);

    Serial.print("Key: ");
    Serial.print(key);

    String message = String(i);

    Serial.print(", index: ");
    Serial.println(message);

    root.set(key, i);
  }

  root.printTo(Serial);
}

This outputs on the serial terminal:

Key: pin_1, index: 1
Key: pin_2, index: 2
Key: pin_3, index: 3
Key: pin_4, index: 4
Key: pin_5, index: 5
Key: pin_6, index: 6
Key: pin_7, index: 7
{"pin_7":7}

So only the last iteration of the loop is added to the object. I guess the same value is being overwritten in each iteration, but I can't figure out why.

I'm using v5.0beta1. I know you don't encourage the use of String() but I tried to figure out a way to do this with chars and it was even less successful (meaningless garbage was printed, mostly).

Any help would be greatly appreciated! This is an excellent tool - thanks a lot for sharing it.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions