Parse content of json in React - reactjs

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.

Related

Reading JSON elements from a field value using REACT

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!

Why is Array.push() throwing an error but Array.concat() does not?

I am trying to add an array to an existing array. The initial data is like this:
props: {
ItemData: // This prop gets populated with data from the parent component. That data comes from a Vuex store.
{
type: Array,
default: null
}
}
setup(props) {
const Item = ref(props.ItemData);
onMounted( ()=> {
Form.Title = Item[0].Title
Form.Files = Item[0].Files
}
)
}
Which results in something like this:
Form = reactive({
Title: null,
Files: [
{name: "photo", extension: ".webp" size: '1024'},
{name: "doc", extension: ".pdf" size: '2048'}
]
)}
The data in Form.Files comes from a prop that is sent to this component from Vuex data:
Form.Files may also be an empty array [ ] if there are no existing files when the form is loaded.
When the user adds new files, the data for the new files is like this:
NewFiles = [
[
File,
{name: "newphoto", extension: ".jpg", size: "1024" }
],
[
File,
{name: "newdoc", extension: ".docx", size: "2048" }
]
]
File is the file object itself as selected via an input field e.g. <input multiple type="file" />
So how do we add NewFiles to Form.Files? I tried the following:
Form.Files.push(...NewFiles);
That somewhat works in that the Vue debugger shows the NewFiles array added to Form.Files, but it thrown an error of [vuex] do not mutate vuex store state outside mutation handlers. and the rest of the code fails.
So I tried concat() which works:
const AllFiles = Form.Files.concat(NewFiles);
Form.BroadcastFiles = AllFiles;
There's no errors but I don't understand why push() would cause a Vuex error when I'm not touching any Vuex state, and even if I was, why doesn't the contact() cause the same error?
.concat returns a new array with both the current items and the new ones where .push modifies the current array instead of returning a new one.
If that array was initially loaded from vuex it results in an unwanted mutation of the store.
Edit:
In the store
mutations: {
addFile(state, file) {
state.ItemData[0].Files.push(file);
},
}
In the component
NewFiles.forEach(file => store.commit("addFile", file));
I suggest you check this article about the use of spread operator in Javascript, and array reference How to Use the Spread Operator (…) in JavaScript especially the "A note about copying by reference" section. So basically you are mutating the state of Form.Files while using concat and you are losing the reference using the spread operator. One solution can be:
let AllFiles = [...Form.Files];
AllFiles.concat(NewFiles);
Form.BroadcastFiles = AllFiles;

Read multiple JSON files as one array

I currently have two JSON files that my array needs to read. Is there a way for me to read them as one array?
I've already tried putting both in a constant variable but it did not work. It was something like this which obviously is not the solution:
const var = [{json_file_1}, {json_file_2}];
I did also try lodash but I still didn't find the solution but I also have a console.log line for the code above.
console.log(_.flattenDeep(ThisFunction(var)));
ThisFunction() reads the contents of my json.
Here is my current array. It is only reading one json file:
const option = json_file_1
.map(group => (
<div key={group.title}>
<div>
{group.title}
</div>
{group.child_one.map(object => (
<div key={object.title}>
{object.title}
</div>
))
</div>
));
Both of JSON files go something like this:
[
{
"title": "this title",
"child_one": [
{
"content_1",
"content_2"
}
],
"child_two": [
{
"title" "this title",
"something": "something else"
},
{
"title" "this title",
"something": "something else"
}
]
}
]
The output should read the two files as one array. Once this is done, will I be able to integrate more JSON files to be read?
The reason you could't do it with
const var = [{json_file_1}, {json_file_2}];
is that you create two object in your array. However you can simply use spread operator.
So you can use it like this and pass this var to your component.
const var = [...json_file_1, ...json_file_2];
If couldn't explain it clearly please say so I can describe with more detail.
I might have found a solution but I don't believe this is the best since I am getting loads of console errors because some of my dummy data are the same
const var = [{json_file_1}, {jsone_file_2}];
and I passed it to my AutoComplete input
<AutoComplete onSearch={_.flattenDeep(ThisFunction(var))}></AutoComplete>
As mentioned above, ThisFunction() reads the arrays and nested arrays inside my JSON file

Parsing through object saved in session storage

So, I have assigned an object with two properties, the first one "items" is an array of objects saved in session storage
[{"id": 0, "name": "example"}]
the second one is just a string
"this is an example"
When I console.log postingItems it works properly and I find the object was merged
method = (e) => {
const postingItems = Object.assign({}, {
items: sessionStorage.getItem("items1"),
method: sessionStorage.getItem("method")
});
sessionStorage.setItem("items", postingItems)
console.log(postingItems)
}
but when I save postingItems in a sessionStorage and then I console.log it shows me this on the console [Object Object]
sessionStorage.setItem("finalItems", postingItems);
console.log(sessionStorage.getItem(finalItems));
You need to stringify your object first and then parse on load/get time
sessionStorage.setItem("finalItems", JSON.stringify(postingItems));
console.log(JSON.parse(sessionStorage.getItem("finalItems")));

Converting JSON object format using angularjs

I am new to Angularjs.I want to change the format of the JSON object code which I am getting into some new format.Below is the format.
$scope.filters={"filters":
[{"filterId":"106","filtername":"Service Line","filterValue":"ADI"},
{"filterId":"107","filtername":"Service Line","filterValue":"L"},
{"filterId":"108","filtername":"Service Line","filterValue":"M"},
{"filterId":"109","filtername":"Location","filterValue":"N"},
{"filterId":"110","filtername":"Band","filterValue":"O"}
]};
I want this to be changed into below format using angularjs.
$scope.filters=[{"filters":
{"ServiceLine":["ADI","L","M"],
"Location":["N"],
"Band":["0"]}
}] ;
Can anyone guide me here?
I agree with kachhalimbu that you can use underscore.js or lodash.js and use it's map function to transform you json object to another form.
If you still want to transform without using another framework you can do something like this:
var filterObject = { "filters": {} };
angular.forEach($scope.filters.filters, function(filter) {
if(!filterObject.filters[filter.filtername]) {
filterObject.filters[filter.filtername] = [];
}
filterObject.filters[filter.filtername].push(filter.filterValue)
});
filterObject will contains that format you want to use, after that you can do something like this:
$scope.filters = [];
$scope.filters.push(filterObject);

Resources