0

I wonder if it's possible to place variables into a JSON string value.

Some example: (file.json)

{
  "type": "description",
  "description": "${this.name} is ${this.age} years old. ${this.name}'s favorite color is ${this.favColor}"
}

Then in React:

data = require("file.json);
name = "John";
age = 20;
favColor = "blue";

render function...

render() {
  return() {
    <p>{this.data.description}</p>
  }
}

Any way to do something like this? The goal is to replace the variables automatically.

halfer
  • 19,824
  • 17
  • 99
  • 186
redmaster
  • 95
  • 1
  • 12
  • You can certainly do that, but you will have to do a manual string find & replace. You can find how to do this pretty quickly. – MauriceNino Jan 18 '22 at 11:40
  • This isn't possible, but you can write a `Person` class, initialize it using the JSON data, then make `description` a function that fills in the data. –  Jan 18 '22 at 11:41
  • I wanted to avoid find&replace, I thought there is a way to automatically replace vars like in php. – redmaster Jan 18 '22 at 11:42
  • find and replace can be done automatically if you write a dedicated function for it. How much more automatic can it get? – MauriceNino Jan 18 '22 at 11:44
  • @ChrisG this was just an example. In my case the description is totally different for every object so it must be contained in the JSON – redmaster Jan 18 '22 at 11:44
  • @MauriceNino Yes I will go that way. I just thought there is a way to replace it automatically. – redmaster Jan 18 '22 at 11:45
  • As already said, that **is** automatic. If you want to achieve something else, what is it? – MauriceNino Jan 18 '22 at 11:46

1 Answers1

1

You can do a manual string find & replace. Something like the following answer will be ok: https://stackoverflow.com/a/1408373/9150652

This could then look something like the following in your React Component:

// Your JSON data as string
const json = `{
  "type": "description",
  "description": "{name} is {age} years old. {name}'s favorite color is {favColor}"
}`

// method to find and replace interpolate values
const interpolate = (str, values) => {
  return str.replace(/{([^{}]*)}/g,
      (a, b) => {
          const r = values[b];
          return typeof r === 'string' || typeof r === 'number' ? r : a;
      }
  );
};

const SomeComponent = () => {
  const values = {
    name: 'John',
    age: 27,
    favColor: 'red'
  };

  // Interpolate before parsing the JSON!
  const parsedJson = JSON.parse(interpolate(json, values));

  // Now you can use the object with the correct values filled in
  return <p>{parsedJson.description}</p>;
}

If you use Class components, you could even try passing in this instead of values and use local values, similar to how you described it in your question
Should (maybe) work out of the box aswell.

MauriceNino
  • 6,214
  • 1
  • 23
  • 60