4

I am trying to open a local JSON file and have the information displayed on my app.

The code seems to run but the JSON information doesn't display. How do I get the JSON information, name & age fields to display?

JSON file:

[
    {
        "name": "George",
        "age": "25"
    },
    {
        "name": "Sarah",
        "age": "42"
    }
]

App.js:

import * as myfile from './myfile.json'

const name = myfile.name;
const age = myfile.name;

export default class App extends React.Component {
  render() {
    return (
      <View style={styles.container}>
        <Text>This is name: {name} This is age: {age}
        </Text>
      </View>
    );
  }
}
axell2017
  • 41
  • 5

2 Answers2

4

So you are accessing an array, there is no myfile.name to assign to const name, you can, however, do something like this; const name = myfile[0].name for George's information only.

Conclusively, you are not extracting information properly from JSON.

P.S., if you can tell me what is the expected behavior, I can help you out.

0

That's because your myFile isn't an object but array.

Use the map array method:

...
 <View style={styles.container}>
       {myFile.map(({ name, age }) => (
        <Text>This is name: {name} This is age: {age}
        </Text>
       )}
 </View>
...

Hope that helped!
Hasan Sh
  • 1,018
  • 9
  • 16