我正在开发一个与JW play API交互的React应用程序。API希望我以JSON格式发送数据。问题是我需要将动态输入数据嵌入到JSON字符串中。我不知道该怎么做。请帮帮我。
JSON对象:
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 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>
)
}