你好,我想从本地Machine中的JSON文件中解析Json数据。这是我的代码var data_local = require("../data/StudentList.json");
,我想检查控制台我得到了什么,但是我得到了网络故障,请给我完整的示例,如何在React native中从本地文件获取Json解析。这是我的另一行代码控制台console.log(data_local);
答案 0 :(得分:2)
请尝试添加以下代码:
您在“ StudentList.json”文件中的Json代码将如下所示:
[{"id": 1,"name": "Student1"},
{"id": 2, "name": "Student2"},
{"id": 3, "name": "Student3"},
{"id": 4, "name": "Student4"},
{"id": 5, "name": "Student5"},
{"id": 6, "name": "Student6"},
{"id": 7, "name": "Student7"},
{"id": 8, "name": "Student8"},
{"id": 9, "name": "Student9"},
{"id": 10, "name": "Student10"}]
您用于访问json数据的代码如下:
import React, { Component } from 'react';
import { View, Text, FlatList} from 'react-native';
import studentList from '../data/StudentList.json';
class DemoApp extends Component {
render() {
return (
<View style={{flex: 1, flexDirection: 'column'}}>
<Text >
Student List
</Text>
<FlatList
data={studentList}
showsVerticalScrollIndicator={false}
renderItem={({item}) =>
<View >
<Text>{item.name}</Text>
</View>
}
keyExtractor={(item, index) => index.toString()}
/>
</View>
);
}
}
export default DemoApp;
答案 1 :(得分:0)
您的json文件应如下所示:
Demo.json
{"name":"Rifat"}
以这种方式导入json文件
import Demo from './demo.json'
console.log(Demo) //output: { name: 'Rifat' }