json_struct icon indicating copy to clipboard operation
json_struct copied to clipboard

Missing support to add Map value in a Map with key name

Open aryamansingh2008 opened this issue 5 months ago • 2 comments

static void from(const fromCustomType&, Token& token, Serializer& serializer) {
  Map nestedMap;
  JS::ParseContext parseContext;
  nestedMap.setValue("innerKey1", parseContext, "value1");
  nestedMap.setValue("innerKey2", parseContext, 42);
  
  Map outerMap;
  outerMap.setValue("regularKey", parseContext, "simpleValue");
  outerMap.setValue("mapKey", parseContext, nestedMap);
  
  TypeHandler<Map>::from(outerMap, token, serializer);
}

The following code produces the below json {"regularKey":[115,105,109,112,108,101,86,97,108,117,101,0],{"innerKey1":[118,97,108,117,101,49,0],"innerKey2":42}}

Adding this in TypeHandler<Map> from method fixes the issue

static inline void from(const Map &from_type, Token &token, Serializer &serializer) { bool isNamedValue = token.name.data != nullptr; if (!isNamedValue) { for (auto &token : from_type.tokens.data) { serializer.write(token); } return; }

Token nameToken;
nameToken.name_type = token.name_type;
nameToken.name = token.name;
nameToken.value_type = Type::ObjectStart;
nameToken.value = DataRef("{");
serializer.write(nameToken);

// Write the Map's inner content (skip the outer object braces)
if (from_type.tokens.data.size() >= 2 && 
    from_type.tokens.data[0].value_type == Type::ObjectStart &&
    from_type.tokens.data.back().value_type == Type::ObjectEnd) {
  // Write only the inner tokens (between outer braces)
  for (size_t i = 1; i < from_type.tokens.data.size() - 1; ++i) {
    serializer.write(from_type.tokens.data[i]);
  }
}

// Close the nested object
Token endToken;
endToken.value_type = Type::ObjectEnd;
endToken.value = DataRef("}");
serializer.write(endToken);

}

aryamansingh2008 avatar Jun 10 '25 08:06 aryamansingh2008

I would be happy to create a Pull Request for the fix. Let me know if I can do that.

aryamansingh2008 avatar Jun 10 '25 09:06 aryamansingh2008

Hey, I just pushed your fix with some slight modifications, and a test. Can you please verify that this is inline with what you had in mind.

https://github.com/jorgen/json_struct/commit/439fb62a87f3acd880b909f68fe0122c38df9b7e

jorgen avatar Jun 10 '25 23:06 jorgen

Thanks, yeah the changes look good and work correctly for the scenario that I shared.

aryamansingh2008 avatar Jun 11 '25 05:06 aryamansingh2008