Skip to content
GitLab
Projects Groups Snippets
  • /
  • Help
    • Help
    • Support
    • Community forum
    • Submit feedback
    • Contribute to GitLab
  • Sign in / Register
  • A ArduinoJson
  • Project information
    • Project information
    • Activity
    • Labels
    • Members
  • Repository
    • Repository
    • Files
    • Commits
    • Branches
    • Tags
    • Contributors
    • Graph
    • Compare
  • Issues 24
    • Issues 24
    • List
    • Boards
    • Service Desk
    • Milestones
  • Merge requests 0
    • Merge requests 0
  • CI/CD
    • CI/CD
    • Pipelines
    • Jobs
    • Schedules
  • Deployments
    • Deployments
    • Environments
    • Releases
  • Packages and registries
    • Packages and registries
    • Package Registry
    • Infrastructure Registry
  • Monitor
    • Monitor
    • Incidents
  • Analytics
    • Analytics
    • Value stream
    • CI/CD
    • Repository
  • Wiki
    • Wiki
  • Snippets
    • Snippets
  • Activity
  • Graph
  • Create a new issue
  • Jobs
  • Commits
  • Issue Boards
Collapse sidebar
  • Benoît Blanchon
  • ArduinoJson
  • Issues
  • #84
Closed
Open
Issue created Jun 25, 2015 by Administrator@rootContributor

Adding keys to object in a loop

Created by: 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.

Assignee
Assign to
Time tracking