Search code examples
reactjsjsoninputdynamicembed

How to embed dynamic data into a JSON string


I'm working on a React app that interacts with JW Playe API. The API wants me to send data in JSON format. The problem is that I need to embed dynamic input data into that JSON string. I don't know how to do that. Please help me out.

Here is the JSON object:

const data =
      '{ "upload": { "method": "fetch", "download_url": I NEED TO PUT DATA COMING FROM REACT STATE (Input) HERE }, "metadata": {"title": "My Fetch Video", "author": "Dzenis H."} }';

Solution

  • You can write something like this:

    const App = () => {
      const [url, setUrl] = useState('');
      const data = '{ "upload": { "method": "fetch", "download_url": "I NEED TO PUT DATA COMING FROM REACT STATE (Input) HERE" }, "metadata": {"title": "My Fetch Video", "author": "Dzenis H."} }';
    
      const updateJson = () => {
        let parseData = JSON.parse(data);
        parseData.upload.download_url = url;
        let converted = JSON.stringify(parseData);
        console.log(converted);
      }
    
      return (
        <div>
          <input type="text" value={url} onChange={e => setUrl(e.target.value)} />
          <button onClick={updateJson}>Update</button>
        </div>
      )
    }