I am using React.js and have a questions.JSON file in which I store the data. Now the data in the JSON file is encoded with % characters but when I fetch the data from the file, it shows up with the % characters.
Here's the JSON file example:
{
"category": "Entertainment%3A%20Video%20Games",
"type": "multiple",
"difficulty": "hard",
"question": "What%20was%20the%20name%20of%20the%20hero%20in%20the%2080s%20animated%20video%20game%20%27Dragon%27s%20Lair%27%3F",
"correct_answer": "Dirk%20the%20Daring",
"incorrect_answers": [
"Arthur",
"Sir%20Toby%20Belch",
"Guy%20of%20Gisbourne"
]
},
Here's the React code:
const getData = () => {
fetch('questions.json', {
headers: {
'Content-Type': 'application/json',
Accept: 'application/json',
},
})
.then(function (response) {
return response.json()
})
.then(function (myJson) {
setQuestions(myJson)
})
}
useEffect(() => {
getData()
}, [])
if (undefined !== questions && questions.length) {
return (
<div className='container'>
<div className='question-number'>
<h2>Question Number</h2>
<p>{questions[0].category}</p>
<p>Difficulty: {questions[0].difficulty}</p>
</div>
<div className='question'>{questions[0].question}</div>
<div className='answer-box'>
<button className='buttons'>{questions[0].correct_answer}</button>
<button className='buttons'>
{questions[0].incorrect_answers[0]}
</button>
<button className='buttons'>
{questions[0].incorrect_answers[1]}
</button>
<button className='buttons'>
{questions[0].incorrect_answers[2]}
</button>
</div>
</div>
)
} else {
return <h1>Loading Question</h1>
}
I'm quite new to React.js so if I am missing something obvious, please be patient with me.
As darklightcodes comment said, you can use decodeURIComponent. Here's a simple implementation for that, note that it relies on the objects having the structure in your example:
const decode = (obj) => {
const res = {};
for (const [key, value] in obj) {
if (typeof value === 'string') {
// Decode strings directly
res[key] = decodeURIComponent(value);
} else {
// For arrays, decode each string containes
res[key] = value.map(str => decodeURIComponent(str));
}
}
}
const getData = () => {
fetch('questions.json', {
headers: {
'Content-Type': 'application/json',
Accept: 'application/json',
},
})
.then(function (response) {
return response.json()
})
.then(function (myJson) {
// Decode the questions
setQuestions(myJson.map(question => decode(question)))
})
}
useEffect(() => {
getData()
}, [])