Search code examples
typescript

How can I use a variable as a field name in JSON stringify?


I'd like to be able to dynamically created a JSON object using a variable as the field name.

I've worked out how to set the field value from a variable using $() but it doesn't work for the field name.

    const body: string = JSON.stringify({
      '__metadata': {
        'type': listItemEntityTypeName
      },
      `${FIELD_NAME}`: `${FIELD_VALUE}`
    });

The error I get in VS Code is:

[ts] Cannot invoke and expression whose type lacks a call signature. Type '{ '__metadata': { 'type':string; }; }' has no compatible call signatures. [2349] [ts] Property assignment expected. [1136]

I'm using typescript and react. I'm fairly new JavaScript so forgive me if I'm missing something obvious.


Solution

  • Anything that goes inside JSON.stringify should be a valid JSON Object

    const body: string = JSON.stringify({
      '__metadata': {
        'type': listItemEntityTypeName
      },
      [FIELD_NAME]: `${FIELD_VALUE}`   // FIELD_VALUE should also be fine, if you dont want to convert it to string.
    });
    

    removing the string literal in the key can give you a valid JSON and hoepfully resolve the error