Home > Software engineering >  Create config Java script file with dynamic key
Create config Java script file with dynamic key

Time:08-25

I have a config file as shown below

import { small,vario,large } from "./../../configs/response.constants";
export const barChartColorConfig = {
  [small]:"rgb(149, 206, 255)",
  [vario]:"rgb(92, 92, 97)",
  [large]:"rgb(166, 253, 147)"
};

It is a Js file where key (small,vario,large) are dynamic string values coming from response.constants file

export const small="small";
export const vario="vario";
export const large='large';

when i tried to put in JSON validation online it say invalid

Is there a way to write [small] in some other way in the config.js

CodePudding user response:

The JSON validator you're using may not correctly recognize Computed Property Names, which are supported in ES5.

CodePudding user response:

JSON is not the same as JavaScript. Although you can create strings containing proper JSON-formatted strings inside of JavaScript, they're distinct concepts. Here:

export const barChartColorConfig = {
  [small]:"rgb(149, 206, 255)",
  [vario]:"rgb(92, 92, 97)",
  [large]:"rgb(166, 253, 147)"
};

You're creating a plain JavaScript object. It's not JSON. If you tried to validate the content of the object as JSON, it would fail - because it's JavaScript syntax and not a JSON string.

If you stringified the object after its creation and tried to validate it, you'd get:

const small = "small";
const vario = "vario";
const large = 'large';
const barChartColorConfig = {
  [small]: "rgb(149, 206, 255)",
  [vario]: "rgb(92, 92, 97)",
  [large]: "rgb(166, 253, 147)"
};

const json = JSON.stringify(barChartColorConfig);
console.log(json);

{"small":"rgb(149, 206, 255)","vario":"rgb(92, 92, 97)","large":"rgb(166, 253, 147)"}, which is valid JSON.

So even if a JSON formatter says that your JavaScript markup with bracket notation is invalid JSON, that's completely normal and expected. You aren't doing anything wrong.

  • Related