I’m using REACT to read the value from an input field containing a JSON object.
I’m able to get the JSON string value into a const containing the following:
{"name":"This is the name element"}
But when I try to extract the value of the "name" element from the JSON, I get an "undefined" response.
When I get the same JSON text from a js file like this:
export default
{"name":"This is the name field"}
and import it using:
import JSONObject from './JSONObjectFile'
Then it work fine.
What do I need to do to achieve the same thing when retrieving the JSON object from the text field on the HTML page?
Here’s the whole code:
import './App.css';
import JSONObject from './aa_DDFFormConfigJSON'
function App() {
var myJSON;
function ConfigJSONReady(event) {
myJSON = document.getElementsByName("myJSONField")[0].value;
//This returns "undefined" instead of the actual "name" element value
console.log("myJSON.name using input field: " + myJSON.name);
// This is the same JSON object from a file, but it works fine
myJSON = JSONObject;
console.log("myJSON.name using file import: " + myJSON.name);
}
return (
<div>
<header>
Everything here is in a REACT App
<p>Success!!</p>
</header>
<form>
<textarea rows="10"
cols="200"
maxlength="5000"
id='myJSONField'
defaultValue='{"name":"This is the name field"}'>
</textarea>
<input
name="DDFConfigJSONReady"
id="DDFConfigJSONReady"
type="checkbox"
onChange={ConfigJSONReady}
/>
</form>
</div>
);
}
export default App;
>Solution :
Values read from input fields are of string type, which means, your JSON object is a string as well. In order to convert your JSON string to a JSON object, you need to use JSON.parse() method.
const myObj = "{"key": "value"}";
const parsedObj = JSON.parse(myObj);
And, if you want to convert your JSON object to a string, you can use JSON.stringify() in the similar manner.
const stringifiedObj = JSON.stringify(parsedObj);
Hope that helps!