ReactJS access JSON object passed from other component - json

I'm new with ReactJs and have this question which right now I find it a bit hard to understand.
I have a component which does a call to retrieve XML object, this XML object is later parsed to JSON object and after passed to other component in order to do some sorting to it.
Right now i'm stuck and unable to access properly the JSON on my second component.
And when I'm trying to do this.props.files.map - it says that map is undefined.
this is the parent component render method where I pass the properties:
render() {
return (
<div>
<List files={this.convertToJson()}/>
</div>
)
}
the JSON that I receive looks like this:
[ {
"$": {
"date": "",
"description": "",
"name": "",
"size": "107829",
"type": "pdf"
}
}, {
"$": {
"date": "",
"description": "",
"name": "",
"size": "682015",
"type": "pdf"
}
}
]
How should I write my second component to get access to this JSON data and later show all properties, i would like to iterate over it and have access to all properties.
this.props.files.map(function($) {
return <li key={$}>{$}</li>
})
this gives me an error with files.map is undefined.
i'm pretty new with this so all help would be useful.
here is the code for this.convertToJson() as requested, if I console log it - it looks like the JSON above.
convertToJson = () => {
return JSON.stringify(this.state.data)

I think the issue might actually be with this.convertToJson()
You need to parse the JSON object into a Javascript object in order to iterate over it in the way you are suggesting.
Check out this example it seems to work correctly.
// This is just mocking your JSON object
const json = JSON.stringify([{
"$": {
"date": "",
"description": "",
"name": "",
"size": "107829",
"type": "pdf"
}
}, {
"$": {
"date": "",
"description": "",
"name": "",
"size": "682015",
"type": "pdf"
}
}
]);
// This is what you care about
const obj = JSON.parse(json);
obj.map(o => {
// You need to get o.$ to get the actual object
console.log(o.$)
});
also in order to pass a component all of the objects properties as props you'll probably need the spread operator <li {...o.$}>{$}</li>
Hope this helps

Related

Ruby: How to parse json to specific types

I have a JSON that I want to parse in Ruby. Ruby is completely new to me, but I have to work with it :-)
Here is my litte snippet, that should do the parsing:
response = File.read("app/helpers/example_announcement.json")
JSON.parse(response)
this works pretty fine. The only downside is, I do not know the properties at the point where I use it, it is not typesafe. So I created the objects for it
class Announcements
##announcements = Hash # a map key => value where key is string and value is type of Announcement
end
class Announcement
##name = ""
##status = ""
##rewards = Array
end
And this is how the json looks like
{
"announcements": {
"id1" : {
"name": "The Diamond Announcement",
"status": "published",
"reward": [
{
"id": "hardCurrency",
"amount": 100
}
]
},
"id2": {
"name": "The Normal Announcement",
"players": [],
"status": "published",
"reward": []
}
}
}
So I tried JSON parsing like this
response = File.read("app/helpers/example_announcement.json")
JSON.parse(response, Announcements)
But this is not how it works^^can anybody help me with this?

How to access nested json inside jsx component in react native?

I am trying to list the server response , but some mistake is their in my code about accessing nested json..Following is the structure of json
Updated:
{
"child": [],
"courses": [{
"data": {
"name": "Student 1",
"date_created": 1514610451,
"total_students": 4,
"seats": "",
"start_date": false,
"categories": [{
"name": "Subject",
"slug": "Subject"
}],
"intro": {
"id": "1",
"name": "Main Admin",
"sub": ""
},
"menu_order": 0
},
"headers": [],
"status": 200
}]
}
And my react part is
render(){
return this.state.course.map(course =>
<Text style={styles.userStyle}>{course.courses.data.map(datas => datas.name)}</Text>
);
}
Please help me to figure out the mistake.I am getting this.state.course.map is not a function.My fetch request is as follows
state= {course:[]};
componentWillMount(){
fetch('https://www.mywebsite.com/' + this.props.navigation.state.params.id)
.then((response) => response.json())
.then((responseData) => this.setState({course: responseData}))
}
So you would need to show us how this.state is set, but if you're doing something like this.setState(jsonObject), the property you are looking for seems to be this.state.courses. This would access the array of courses. However, in the subsequent lines you try to access course.courses, which suggests you're setting the state like this.seState({course: jsonObject}) so it's not clear.
I'd say if you fix the first problem, you'll immediately hit another one because it doesn't look like data is an array but an object, so trying to call map on it is unlikely to do what you want (unless you've been playing with prototypes).
EDIT:
In response to the new info, I recommend the following:
render(){
if(this.state.course && this.state.course.courses) {
return this.state.course.courses.map(course =>
<Text style={styles.userStyle}>{course.data.name}</Text>
);
} else {
return [];
}
}

Access Array inside an object (json)

I have this json file and I want to access the array that is inside this object:
best-sellers": [
{
"title": "Chuteira Nike HyperVenomX Proximo II Society",
"price": 499.90,
"installments": {
"number": 10,
"value": 49.90
},
"high-top": true,
"category": "society",
"image": ""
},
{
"title": "Chuteira Nike HyperVenom Phantom III Cano Alto Campo",
"price": 899.90,
"installments": {
"number": 10,
"value": 89.90
},
"high-top": true,
"category": "campo",
"image": ""
}
}
]
This is the code on my component:
ngOnInit(): void {
this.service
.lista()
.subscribe(chuteiras =>{
this.chuteiras = chuteiras;
})
}
and my template looks like this:
<div *ngFor="let chuteira of chuteiras.best-sellers">
But angular is not reconigzing it the `best-sellers", here's the error that I'm getting:
Cannot read property 'best' of undefined
Just use bracket notation,
<div *ngFor="let chuteira of chuteiras["best-sellers"]">
well,that's one way of doing it but angular 6 came with a simple solution. when i was faced with this problem i myself resolved to this solution but it didn't work for me so after searching and making my own touches i ended up with this solution.
1.create the function to receive the JSON data in my case i used a web API
getTrending() {
return this.http.get(https://api.themoviedb.org/3/trending/all/day?api_key=${this.api_key});
}
2.call the function in my case i used a service, so after import it to my component i simply added this
showPopular(): void {
this.api.getTrending().subscribe((data: Array<object>) => {
this.list = data['results'];
console.log(this.list);
});
}
as you can see the data variable only accessed the information i required.

How to return a subcollection (or object) in json without including all attributes

I am using mongoose as JSON Schema and node.js with it. Need not say, I am new to both. I have been struggling through the day to get this thing work for me but couldn't. Finally, the only solution was to get help from some real nice people out here.
Here is my schema definition -
UserName = {
"properties": {
userURL: {
"description": "URL of this resource",
"type": "string"
},
userName : {
"description": "UserName",
"type": "string",
"required": true
},
}
}
When I make a get call to it, it returns the response in following format -
[
{
"_id": "54c5ede55c82c4bd6abee50a",
"__v": 0,
"properties": {
"userURL": "http://localhost:3000/54c1d6ae441ae900151a6520",
"userName ": "testUser"
}
}
]
Now my requirement is to return the response in following format -
[
{
"_id": "54c5ede55c82c4bd6abee50a",
"userURL": "http://localhost:3000/54c1d6ae441ae900151a6520",
"userName ": "testUser"
}
]
i.e without version and properties tags. I am able to get away with version using following code but properties seems to be tricky thing -
.get(function(request, response) {
UserSchemaModel.find().select('properties.userURL properties.userName').exec (function (err, resObj) {
if (err)
response.send(err);
else{
response.json(resObj);
}
});
});
But it still has properties field :( -
[
{
"_id": "54c5ede55c82c4bd6abee50a",
"properties": {
"userURL": "http://localhost:3000/54c1d6ae441ae900151a6520",
"userName ": "testUser"
}
}
]
I did some google around select as, alias name in select,population in mongoose but no luck.
Kindly suggest. With best Regards.
Just make a new object
response.json(
{
"_id": resObj["_id"],
"userURL": resObj["properties"]["userUrl"],
"userName": resObj["properties"]["userName"]
}
);
Update: Since resObj is an array (as per your comment), you can use Array.prototype.map() to transform them into the right format like so:
response.json( resObj.map(function(o){
return {
"_id": o["_id"],
"userURL": o["properties"]["userUrl"],
"userName": o["properties"]["userName"]
};
})
);
This will return a list of transformed objects that then get passed into the response.json() method.

angularJS $resource response is both array AND object

got this json file:
[
{
"name": "paprika",
"imgSrc": "img/paprika.jpg"
},
{
"name": "kurkku",
"imgSrc": "img/kurkku.jpg"
},
{
"name": "porkkana",
"imgSrc": "img/porkkana.jpg"
},
{
"name": "lehtisalaatti",
"imgSrc": "img/lehtisalaatti.jpg"
},
{
"name": "parsakaali",
"imgSrc": "img/parsakaali.jpg"
},
{
"name": "sipula",
"imgSrc": "img/sipuli.jpg"
},
{
"name": "peruna",
"imgSrc": "img/peruna.jpg"
},
{
"name": "soijapapu",
"imgSrc": "img/soijapapu.jpg"
},
{
"name": "pinaatti",
"imgSrc": "img/pinaatti.jpg"
}
]
Which I successfully fetch in a factory:
factory('getJson', ['$resource', function($resource) {
return $resource('json/vegs.json', {}, {
query: {method:'GET', isArray:true}
});
}]);
in my Controller I can get the json's file content:
var vegs = getJson.query();
$scope.vegs = vegs;
console.log(vegs)
console.log(typeof vegs)
The weird part is the first console.log produces an array of objects, as expected.
The second console says it's an "object", and not an array.
I can get the .json content to my view using {{vegs}}, and I can use ng-repeat as well, tho in the controller I can't do vegs[0] or vegs.length. It comes out empty.
I'm breaking my head on this for over 3 hours now :)
This isn't an 'answer'. Just an observation on one part of your issue. (Sorry, can't comment yet...new to stackoverflow).
Just a note on your comment that "The second console says it's an "object", and not an array." Using typeof on an array will always return "object".
There are various (and debated, it seems) ways to test if it's an array--Array.isArray(obj) for example.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray