Reading JSON elements from a field value using REACT - reactjs

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 works 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;

You are using the wrong API to get the textarea value, you didn't give the name attribute value to the element.
<textarea rows="10"
cols="200" // you are missing `name="myJSONField"`
maxlength="5000"
id='myJSONField'
defaultValue='{"name": "This is the name field"}'>
</textarea>
Instead, you can use document.getElementById() as you already have give an id to the element.
And the value you got from the element is a text, you should parse it to JSON using JSON.parse().
So the code will look like this:
myJSON = document.getElementById("myJSONField").value;
//This returns "undefined" instead of the actual "name" element value
console.log("`myJSON.name` using input field: " + JSON.parse(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);
Live demo here: https://codesandbox.io/s/funny-raman-ktvdzi?file=/src/App.js:141-513

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!

Related

Parse content of json in React

I've a response JSON which i would like to parse. Specifically, I am interested in visualizing in an HTML the values contained in the "raw".
Below is an example of the JSON file.
{
"values":{
"first":{
"raw":"first value",
"encoded":"1019570973946118"
},
"second":{
"raw":"second value",
"encoded":"1822871964691"
}
}
}
Using JSON.stringify I can see the entire JSON but, of course that is not my intention.
Thank you
Edit:
I'm sorry, I was very superficial in my initial description. I would like to extract the value contained in raw of this example json file and display it in a react component in HTML. Something like: {JSON.stringify(raw)}
Parsing a JSON string to an actual javascript object is NOT done by JSON.stringify() but by JSON.parse().
So in order to retrieve the raw part you would have to do this:
const response = `{
"values":{
"first":{
"raw":"first value",
"encoded":"1019570973946118"
},
"second":{
"raw":"second value",
"encoded":"1822871964691"
}
}
}`;
const parsedJSON = JSON.parse(response)
for (const key of parsedJSON.values.keys()) {
const raw = parsedJSON.values[key].raw;
console.log(raw)
}
The variable raw could be used as a prop, state, etc. now.

In my rest webservice request for react using axios, the response json contains html div element. how can I get the value of this element?

[
{
"title":"Palmeiras - Coritiba",
"embed":"<div style='width:100%;height:0px;position:relative;padding-bottom:calc(56.25% + 335px);' class='_scorebatEmbeddedPlayerW_'><iframe src='https://www.somestream.com/embed/g/934437/?s=2' frameborder='0' width='560' height='650' allowfullscreen allow='autoplay; fullscreen' style='width:100%;height:100%;position:absolute;left:0px;top:0px;overflow:hidden;' class='_scorebatEmbeddedPlayer_'></iframe></div>",
"url":"https://www.some.com/coritiba-vs-palmeiras-live-stream/",
"thumbnail":"https://www.somestream.com/og/m/og934437.jpeg",
"date":"2020-10-14T21:00:00+0000",
"side1":{
"name":"Palmeiras",
"url":"https://www.some.com/live-stream/palmeiras/"
},
"side2":{
"name":"Coritiba",
"url":"https://www.some.com/live-stream/coritiba/"
}
}
]
I want to get the title, thumnail, and video, date feilds from this response but unable to get the video because it is in div element.
You need to use DOMParser to read the HTML string into a JavaScript document. The you can use DOM methods like querySelector and getElementById on it.
Here's a function to return the video src from an HTML embed string.
const getEmbedSrc = (embed) => {
const parser = new DOMParser();
const doc = parser.parseFromString(embed, "text/html");
return doc.getElementsByTagName('iframe')[0].src;
}
const embed = "<div style='width:100%;height:0px;position:relative;padding-bottom:calc(56.25% + 335px);' class='_scorebatEmbeddedPlayerW_'><iframe src='https://www.somestream.com/embed/g/934437/?s=2' frameborder='0' width='560' height='650' allowfullscreen allow='autoplay; fullscreen' style='width:100%;height:100%;position:absolute;left:0px;top:0px;overflow:hidden;' class='_scorebatEmbeddedPlayer_'></iframe></div>";
console.log(getEmbedSrc(embed));
Alternatively, you can find a match using regex.

Replace string with react component with .replace

I have a long text (string), I want the user to be able to highlight any word he wants, and make this word a Tag component.
function highlightingString() {
document.onmouseup = () => {
const myHighlightedString = window.getSelection().toString(); // Gives me the word I highglight
const startHighlightedString = docText.indexOf(myHighlightedString) // Give me the start index of my word in the document
const endHighlightedString = startHighlightedString + myHighlightedString.length // Give me the end index of my word in the document
newDocText = docText.replace(myHighlightedString, <Tag name={"Highlighted"}/>)
setOpenedFile(newDocText)
};
}
Tag component
function Tag({name}){
const color = colors[name];
return <div style={{backgroundColor: color, ...tagStyle}}>{name}<span style={{cursor: "pointer", paddingLeft: '10px'}}</span></div>
}
Example:
Initial document text: "Hello, I would like to order a pizza with peperoni"
If the user selects "pizza with", I would like to happen:
"Hello, I would like to order a Tag name={highlighted} /> peperoni" # Where Tag is simply adding a to the selected word
Instead, I get:
"Hello, I would like to order a [object Object] peperoni"
It seems that I am replacing correctly the string I highlight with the <Tag /> component, however I do not get why is not rendering the text within <span> but [object Object]
Well, replacing part of the string with an object will not magically insert that object into that string :) What it does is converting your object to its string representation (which is [object Object]) and then inserting that representation into the string.
What you want to do is to create a proper React component.
Something like this:
<>
{openFile.textBeforeHighlighted}
<Tag name={openFile.highlighted}/>
{openFile.textAfterHighlighted}
</>
while your handler function sets openFile to something like this:
setOpenFile({
textBeforeHighlighted:textBeforeHighlighted,
highlighted:highlighted,
textAfterHighlighted:textAfterHighlighted
});

How to select all fields including id and name value in select box using Angular JS

I have the select box.
<select ng-model="sub_class_name" class="form-control">
<option ng-repeat="x in myData" value="{{x}}">{{x.sub_class_name}}</option>
</select>
Am passing value to a controller like this :
$scope.alertdata = function() {
var parameter = {
"first_name": $scope.first_name,
"middle_name": $scope.middle_name,
"subclass": [$scope.sub_class_name]
}
}
After printing the parameter
alert(JSON.stringify(parameter));
Am getting stringified JSON output i.e.,
{"first_name":"Prashanth","middle_name":"H","last_name":"Rotti",
"subclass":["{\"sub_class_id\":3,\"sub_class_name\":\"Dependent \"}"]}
I dont want slashes ["{\"sub_class_id\":3,\"sub_class_name\":\"Dependent \"}"]
I want JSON output like this.
{"first_name":"Prashanth","middle_name":"H","last_name":"Rotti",
"subclass":[{"sub_class_id":"3","sub_class_name":"Dependent"}] }
Adding my comment as answer, as it is not possible to format data properly in comment:
**Update **
Since datatype expected is string in JSON format, so you can initialize like this
$scope.sub_class_name = "{}" // Or $scope.sub_class_name ="[]"; based on data type it may be
$scope.alertdata = function() {
var parameter = {
"first_name": $scope.first_name,
"middle_name": $scope.middle_name,
"subclass": [JSON.parse($scope.sub_class_name)]
}
}
alert(JSON.stringify(parameter));
Let me know if you face any issue with this.
Use JSON.parse()
It will do the trick.

React JSX - dynamic html attribute

In JSX, we can indicate attribute value dynamically like:
<div className={this.state.className}>This is a div.</div>
Is it possible to indicate attribute (including attribute name and attribute value) dynamically? Like:
const value = emptyValue ? "" : "value='test'";
<input {value} />
That means, once emptyValue is true, "input" tag should not include "value" attribute (value="" is different from no value attribute, as one is show empty in input field, another is show existing text in input field).
ES6 object expansion only works for objects. Therefore to generate a dynamic attribute, try something like this:
const value = emptyValue ? {} : { value: 'test' }
<a {...value} ></a>
Note value will always be an object.
you can insert whole element in if statement in render function, but before return like this:
render() {
var input = (<input />);
if (!emptyValue) {
input = (<input value='test'/>)
}
return (
<div>
{input}
</div>
)
}

Resources