Not able to parse json file and display data - react native - json

import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View,
Navigator,
TouchableOpacity,
Image,
TouchableHighlight,
Alert,
TextInput
} from 'react-native';
import Button from 'react-native-button'
import {Actions} from 'react-native-router-flux'
import Home from './Home'
export class Temp extends Component{
constructor(props) {
super(props);
this.state = {
data: '',
textinput:'',
}
state={
shouldShow: false
}
}
componentDidMount(){
this._onPressButtonGET();
}
_onPressButtonPOST(){
fetch("url", {
method: "POST",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
"entryDate":"3/2/2017 2:00 AM",
"systol": this.state.textinput,
"mobileType":"ANDROID",
"userName":"menutest",
})})
.then((response) => response.json())
.then((responseData) => {
Alert.alert(
"Blood pressure data",
"Blood pressure data - " + JSON.stringify(responseData)
)
}).catch((error) => {
console.error(error);
})
.done();
}
_onPressButtonGET(){
fetch("url", {
method: "POST",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({"mobileType":"ANDROID","userName":"menutest"})})
.then((response) => response.json())
.then((responseData) => {
this.setState({ data : JSON.stringify(responseData)})
}) .catch((error) => {
console.error(error);
})
.done();
}
render(){
return(
<View>
<TouchableHighlight onPress={this._onPressButtonPOST.bind(this)}>
<Text>Add</Text>
</TouchableHighlight>
<TouchableOpacity style= {{left:300,top:-20, }}
onPress={()=>{ this.setState({ shouldShow: !this.state.shouldShow })}}
><Text>Edit</Text></TouchableOpacity>
{this.state.shouldShow ? <TextInput placeholder='systol'
onChangeText={(text) => this.setState({textinput: text})}
/> : null}
<TouchableHighlight onPress={this._onPressButtonGET.bind(this)}>
<Text>show</Text>
</TouchableHighlight>
<Text>{this.state.data}</Text>
</View>
);
}
}
module.exports = Temp;
I need to parse json file and display the data that is entryDate and systol. but i am not able to parse it. but in the above code i am able to display all the data.
{
"List": [
{
"entryDate": "03/02/2017",
"entryDateTime": "03/02/2017 2:00 AM",
"entryTime": "2:00 AM",
"systol": "120"
},
{
"entryDate": "03/02/2017",
"entryDateTime": "03/02/2017 2:00 AM",
"entryTime": "2:00 AM",
"systol": "121"
},
{
"entryDate": "03/02/2017",
"entryDateTime": "03/02/2017 2:00 AM",
"entryTime": "2:00 AM",
"systol": "120"
},
{
"entryDate": "03/02/2017",
"entryDateTime": "03/02/2017 2:00 AM",
"entryTime": "2:00 AM",
"systol": "122"
},
{
"entryDate": "03/02/2017",
"entryDateTime": "03/02/2017 2:00 AM",
"entryTime": "2:00 AM",
"systol": "123"
}
]
}
this is my json file.
and i want output like:
entryDate:03/02/2017
systol:120
entryDate:03/02/2017
systol:121
entryDate:03/02/2017
systol:122
entryDate:03/02/2017
systol:123

set data state to null
this.state = {
data: null
};
change
this.setState({ data : JSON.stringify(responseData)})
to
this.setState({ data : responseData })
Then display relevant data inside your render like this -
<View>
....
....
{this.state.data &&
this.state.data.List.map((d,i) => (
<View key={i}>
<Text>{d.entryDate}</Text>
<Text>{d.systol}</Text>
</View>
))}
</View>

Related

How to use json file fetch in react native

How should I use json data in flatlist?
This is the code I have
import React, { Component } from 'react'
import { Text, View, Button, YellowBox, FlatList, Image, ScrollView, Dimensions, TouchableHighlight } from 'react-native'
import Swiper from 'react-native-swiper'
import {styles} from '../style/styles'
class NavtexPage extends Component {
constructor(props) {//function
YellowBox.ignoreWarnings([
'Warning: componentWillReceiveProps is deprecated',
'Warning: componentWillUpdate is deprecated',
]);
super(props);
this.state = {
indexPage: 0,
isLoading: true,
}
}
//fetch API
componentDidMount = () => {
fetch('http://localhost:3000/jsondb/2',
{
method: "GET",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
}
})//여기까지 fetch : requests
.then((response) => response.json())//fetch : response
.then((responseData) => {
console.log("성공 : ", responseData);
this.setState({
isLoading: false,
data: responseData
})
})
.catch((error) => {
console.error("api error : " + error.message);
});
}
//_renderItem how to json
_renderItem = ({ item, index }) => {
console.log('json : ', item);
}
render() {
return (
<View style={styles.container}>
<View style={{ flex: 0.1, backgroundColor: 'green' }}>
<Text>NAVTEX</Text>
</View>
<View>
<FlatList//i don't know
style={{ flex: 1, marginTop: 50, borderWidth: 1, borderColor: 'red' }}
data={this.state.data}
numColumns={1}
renderItem={this._renderItem}
// keyExtractor={(item, index) => item.no.toString()}
keyExtractor={(item => )}
/>
</View>//help
</View>
);
}
}
export default NavtexPage;
----------------------------ex.json
[
{
"Page1_1" :
[
{
"main_subject" : "asd",
"sub_subject" : "asd",
"mini_subject" : "asd",
"action" : "asd",
"action_img" : "",
"is_ok" : "1",
},
{
"main_subject" : "" ,
"sub_subject" : "",
"action" : "asd",
"action_img" : "",
"is_ok" : "",
}
]
},
{
"Page1_2" :
[
{
"main_subject" : "asd",
"sub_subject" : "asd",
"mini_subject" : "asd",
"action" : "asd",
"action_img" : "",
"is_ok" : "1",
},
{
"main_subject" : "" ,
"sub_subject" : "",
"action" : "Ping to 155.155.1.2 (NAVTEX TX2 at HF Site)",
"action_img" : "",
"is_ok" : "",
}
]
}
]
Firstly, you need to parse the json to array or object,then assign it to your flatlist data
.then((responseData) => {
let result = Json.parse(responseData)
// you data is array,and have page
let curPageData = result.page1_1
this.setState({
isLoading: false,
data: curPageData
})
})
You can try map function also.
sample code:-
this.state.data.map((data) => { //main data array
return(
data.map((insideData) => { //you can access page1_1 ... pages
return(
<Text>{insideData.main_subject}</Text>
.....
)
})
)
})

Populating picker in react native through fetch from the server

I am trying to get picker values from the server to my react-native project. this is my JSON data. How do I fetch it for the picker component? I tried all d methods from web results. but I get only a blank screen. Kindly please help
{
"MFBasic": {
"SkinTones": "DARK,FAIR,VFAIR",
"Build": "SLIM,ATHLETIC,PLUMPY",
"Gender": "F,M,T",
"Genre": "ACTION,COMEDY,DRAMA",
"Languages": "ENG,HINDI,TAM",
"MediaModes": "ADS,MOVIES,SHORTFILMS",
"Tags": "BIKES,HOME,JEWELLARY"
},
"Result": "Successfully Loaded MF Basic Details",
"Code": 100
}
App.js
export default class App extends Component {
state = {
PickerValueHolder:[],
Gender:'',
}
componentDidMount() {
fetch('https://movieworld.sramaswamy.com/GetMFBasicDetails.php', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
}).then((response) => response.json())
.then((responseJson) => {
let PickerValueHolder = responseJson.MFBasic;
this.setState({ PickerValueHolder }); // Set the new state
}).catch((error) => {
console.error(error);
});
}
render() {
return (
<View style = {styles.MainContainer}>
{<Picker
selectedValue={this.state.Gender}
onValueChange={(itemValue, itemIndex) =>
this.setState({Gender:itemValue})} >
{ this.state.PickerValueHolder.map((item, key)=>
<Picker.Item label={item.Gender} value={item.Gender} key={key}/>
)}
</Picker>}
</View>
);
}
}
above code is my app.js file. but it returns nothing to the picker.help me please. Thank u.
Looking at the json from your API call
{
"MFBasic": {
"SkinTones": "DARK,FAIR,VFAIR",
"Build": "SLIM,ATHLETIC,PLUMPY",
"Gender": "F,M,T",
"Genre": "ACTION,COMEDY,DRAMA",
"Languages": "ENG,HINDI,TAM",
"MediaModes": "ADS,MOVIES,SHORTFILMS",
"Tags": "BIKES,HOME,JEWELLARY"
},
"Result": "Successfully Loaded MF Basic Details",
"Code": 100
}
The issue that is that you are trying to set a string where it needs an array. You can do it by doing something like this:
let genderString = responseJson.MFBasic.Gender;
let genderArray = genderString.split(',');
this.setState({ PickerValueHolder: genderArray });
let responseJson = {
"MFBasic": {
"SkinTones": "DARK,FAIR,VFAIR",
"Build": "SLIM,ATHLETIC,PLUMPY",
"Gender": "F,M,T",
"Genre": "ACTION,COMEDY,DRAMA",
"Languages": "ENG,HINDI,TAM",
"MediaModes": "ADS,MOVIES,SHORTFILMS",
"Tags": "BIKES,HOME,JEWELLARY"
},
"Result": "Successfully Loaded MF Basic Details",
"Code": 100
}
let genderString = responseJson.MFBasic.Gender;
let genderArray = genderString.split(',');
console.log(genderArray)
Because the items in your array are just strings you cannot access them by using item.Gender that won't work. You need to just access them using item.
I have created an example based on your code and implemented the change from above and fixed the Picker.Item component so it should render now. You can see the working code at the following snack https://snack.expo.io/#andypandy/picker-with-array-of-strings
import React from 'react';
import { Text, View, StyleSheet, Picker } from 'react-native';
import { Constants } from 'expo';
export default class App extends React.Component {
state = {
PickerValueHolder: [],
Gender: ''
}
componentDidMount () {
fetch('https://movieworld.sramaswamy.com/GetMFBasicDetails.php', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
}
}).then((response) => response.json())
.then((responseJson) => {
let genderString = responseJson.MFBasic.Gender;
let genderArray = genderString.split(',');
this.setState({ PickerValueHolder: genderArray });
}).catch((error) => {
console.error(error);
});
}
render () {
console.log(this.state.PickerValueHolder)
return (
<View style={styles.container}>
{<Picker
selectedValue={this.state.Gender}
onValueChange={(itemValue, itemIndex) =>
this.setState({ Gender: itemValue })} >
{ this.state.PickerValueHolder.map((item, key) =>
<Picker.Item label={item} value={item} key={key}/>
)}
</Picker>}
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
paddingTop: Constants.statusBarHeight,
backgroundColor: '#ecf0f1',
padding: 8
}
});

How can I load data from a JSON file which is stored at GitHub in React Native?

I have the following JSON file in my GitHub and want to load it:
{"Cat": [
{"key": "a", "title": "Bangladesh", "image": "https://raw.githubusercontent.com/mudassir21/server/master/img/bangladesh.jpg"},
{"key": "b", "title": "Sports", "image": "https://raw.githubusercontent.com/mudassir21/server/master/img/sports.jpg"},
{"key": "c", "title": "Politics", "image": "https://raw.githubusercontent.com/mudassir21/server/master/img/politics.jpg"},
{"key": "d", "title": "Entertainment", "image": "https://raw.githubusercontent.com/mudassir21/server/master/img/entertainment.png"},
{"key": "e", "title": "Economics", "image": "https://raw.githubusercontent.com/mudassir21/server/master/img/economics.jpg"},
{"key": "f", "title": "Technology", "image": "https://raw.githubusercontent.com/mudassir21/server/master/img/technology.jpg"},
{"key": "g", "title": "Others", "image": "https://raw.githubusercontent.com/mudassir21/server/master/img/m.jpg"}
]}
I tried to use the following code to fetch it:
getMoviesFromApiAsync() {
return fetch('https://raw.githubusercontent.com/mudassir21/server/master/newsCategory.json')
.then((response) => response.json())
.then((responseJson) => {
return responseJson.Cat;
})
.catch((error) => {
console.error(error);
});
}
<FlatList horizontal= {true}
data={this.getMoviesFromApiAsync()}
renderItem={({item}) => (
<TouchableOpacity
style={styles.catOption}
onPress = { ()=> this.setState({ name: item.title })}
>
<Image
style={styles.imgButton}
source={{uri: item.image}}
/>
<Text style={styles.buttonText}>{item.title}</Text>
</TouchableOpacity>
)
}
/>
However, no data is loaded from the JSON file. What's the problem?
As your fetch is triggered when the list is rendered, the result of the fetch is not set. In order to re-render the list with data I would suggest to set the result inside the state of the Component. This will trigger a re-render and you should be able to see the list after the fetch resolves:
class MyComp extends Component {
state = { result: [] }
componentWillMount(){
this.getMoviesFromApiAsync()
}
getMoviesFromApiAsync = () => fetch('https://raw.githubusercontent.com/mudassir21/server/master/newsCategory.json')
.then((response) => response.json())
.then((responseJson) => {
this.setState({ result: responseJson.Cat });
})
.catch((error) => {
console.error(error);
})
render(){
<FlatList data={this.state.result} ... />
}
}
Read this link
Use this code:
import React, { Component } from 'react';
import { ActivityIndicator, ListView, Text, View } from 'react-native';
export default class Movies extends Component {
constructor(props) {
super(props);
this.state = {
isLoading: true
}
}
componentDidMount() {
return fetch('https://facebook.github.io/react-native/movies.json')
.then((response) => response.json())
.then((responseJson) => {
let ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
this.setState({
isLoading: false,
dataSource: ds.cloneWithRows(responseJson.movies),
}, function() {
// do something with new state
});
})
.catch((error) => {
console.error(error);
});
}
render() {
if (this.state.isLoading) {
return (
<View style={{flex: 1, paddingTop: 20}}>
<ActivityIndicator />
</View>
);
}
return (
<View style={{flex: 1, paddingTop: 20}}>
<ListView
dataSource={this.state.dataSource}
renderRow={(rowData) => <Text>{rowData.title}, {rowData.releaseYear}</Text>}
/>
</View>
);
}
}

react native how to filter data with some key object on json

if I have json like this
-----------------
{
title: "The Basics - Networking",
description: "Your app fetched this from a remote endpoint!",
movies: [
{
title: "Star Wars",
category: "space",
releaseYear: "1977"
},
{
title: "Back to the Future",
category: "time"
releaseYear: "1985"
},
{
title: "The Matrix",
category: "scifi",
releaseYear: "1999"
},
{
title: "Inception",
category: "fantasy",
releaseYear: "2010"
},
{
title: "Interstellar",
category: "space"
releaseYear: "2014"
}
]
}
-----------------
I need to filter some data of category = space
but I don't know how to filter data after fetch json form webservice
I want only data form category = space
(It's mean I want to get interstellar and star wars)
and set to datasource
like a " dataSource: ds.cloneWithRows(responseJson.movies)" but this method get all row without filter
componentDidMount() {
return fetch('https://facebook.github.io/react-native/movies.json')
.then((response) => response.json())
.then((responseJson) => {
let ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
this.setState({
isLoading: false,
dataSource: ds.cloneWithRows(responseJson.movies),
}, function() {
// do something with new state
});
})
.catch((error) => {
console.error(error);
});
}
Use Array#Filter like this:
const movies = [{
title: "Star Wars",
category: "space",
releaseYear: "1977",
},
{
title: "Back to the Future",
category: "time",
releaseYear: "1985",
},
{
title: "The Matrix",
category: "scifi",
releaseYear: "1999",
},
{
title: "Inception",
category: "fantasy",
releaseYear: "2010",
},
{
title: "Interstellar",
category: "space",
releaseYear: "2014",
}
];
const space = movies.filter(x => x.category === 'space');
console.log(space);
Here you are another Array#Filter example,
filter posts where userId is 1.
https://jsonplaceholder.typicode.com/posts :
class Data extends React.Component {
constructor(props) {
super(props);
this.state = {
data: []
};
}
componentDidMount() {
return fetch('https://jsonplaceholder.typicode.com/posts')
.then(response => response.json())
.then(data => {
this.setState({ data: data.filter(d => d.userId === 1) })
})
.catch(error => {
console.error(error);
});
}
render() {
return (
<div>
<h1>Posts JSON:</h1>
<pre>
{JSON.stringify(this.state.data, null, 2)}
</pre>
</div>
);
}
}
ReactDOM.render(
<Data />,
document.getElementById('container')
);
<div id="container">
<!-- This element's contents will be replaced with your component. -->
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

Extract data from JSON list in React native

I want to parse a JSON file and display some data on the screen. I am able to display all the data using the following code, but I want to display only entryDate and sysol. Is it possible to use a for loop in _onPressButtonGET() and display data there only?
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View,
Navigator,
TouchableOpacity,
Image,
TouchableHighlight,
Alert,
TextInput
} from 'react-native';
import Button from 'react-native-button'
import {Actions} from 'react-native-router-flux'
import Home from './Home'
export class Temp extends Component{
constructor(props) {
super(props);
this.state = {
data: '',
data1:'',
textinput:'',
entryDate:[]
}
state={
shouldShow: false
}
}
componentDidMount(){
this._onPressButtonGET();
}
_onPressButtonPOST(){
fetch(URL, {
method: "POST",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
"entryDate":"3/2/2017 2:00 AM",
"systol": this.state.textinput,
"mobileType":"ANDROID",
"userName":"menutest",
})})
.then((response) => response.json())
.then((responseData) => {
Alert.alert(
"Blood pressure data",
"Blood pressure data - " + JSON.stringify(responseData)
)
}).catch((error) => {
Alert.alert('problem while adding data');
})
.done();
}
_onPressButtonGET(){
fetch(url, {
method: "POST",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({"mobileType":"ANDROID","userName":"menutest"})})
.then((response) => response.json())
.then((responseData) => {
this.setState({ data : JSON.stringify(responseData) })
data["list"].map(d => this.state.entryDate.push(d.entryDate));
this.setState({ entryDate: jsonResponse.entryDate, systol: responseData.systol })
}).catch((error) => {
Alert.alert('problem while getting data');
})
.done();
}
render(){
return(
<View>
<TouchableHighlight onPress={this._onPressButtonPOST.bind(this)}>
<Text>Add</Text>
</TouchableHighlight>
<TouchableOpacity style= {{left:300,top:-20, }}
onPress={()=>{ this.setState({ shouldShow: !this.state.shouldShow })}}
><Text>Edit</Text></TouchableOpacity>
{this.state.shouldShow ? <TextInput placeholder='systol'
onChangeText={(text) => this.setState({textinput: text})}
/> : null}
<TouchableHighlight onPress={this._onPressButtonGET.bind(this)}>
<Text>show</Text>
</TouchableHighlight>
this.state.entryDate.map( d => (<Text>{d}</Text>));
<Text>{this.state.entryDate}</Text> //not displaying anythong
<Text>{this.state.data && JSON.parse(this.state.data)['entryDate']}</Text> //not displaying anything
<Text>hello{this.state.data}</Text> //printing all data
</View>
);
}
}
module.exports = Temp;
JSON:
{
"List": [
{
"entryDate": "03/02/2017",
"entryDateTime": "03/02/2017 2:00 AM",
"entryTime": "2:00 AM",
"systol": "120"
},
{
"entryDate": "03/02/2017",
"entryDateTime": "03/02/2017 2:00 AM",
"entryTime": "2:00 AM",
"systol": "120"
}
]
}
first initialize entryData as array
this.state = {
entryDate: [],
}
in _onPressButtonGET() use
data["List"].map(d => this.state.entryData.push(d.entryDate));
in render use map to display all data like that
this.state.entryDate.map( d => (<Text>{d}</Text>));
onPressButtonGET(){
fetch(url, {
method: "POST",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({"mobileType":"ANDROID","userName":"menutest"})})
}
.then(response => {
this.setState({entryDate:response.data})
});
renderEntryDate() {
this.state.entryDate.map((item)=>{
<Text>{item.entryDate}</Text>
})
}
render() {
return (
<View>
<Button style= {{
backgroundColor: '#6656B4',
width: 200,
height: 40,
}
onPress={() => this.onPressButtonGET()}
title="Get Weather"
color="#841584"
/>
{this.renderEntryDate()}
<View>
);
}