Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

90
Views
REACTJS Place variables inside JSON string

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.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!