Aleksf
Aleksf

Reputation: 71

how to return json file to React

There is json in the project which contains the data that I need to display in the component. How to correctly access the json file in react and output data from json?

data.json

{
  "dictionary": [
    {
      "index": "1",
      "engwords": "Hello",
      "ruswords": "Привет"
    },
    {
      "index": "2",
      "engwords": "How are you?",
      "ruswords": "Как твои дела?"
    },
    {
      "index": "3",
      "engwords": "How old are you?",
      "ruswords": "Сколько тебе лет?"
    }
  ]
}

component.js

import React, {Component} from "react";
import "./style.scss";
const dictionary = require ('./../../dictionary/dictionary.json');

export default class Test extends Component {
    render() {
        return (
            <div className="test">
                {dictionary.map(elem => (
                    <p>{elem}</p>))}
            </div>
        );
    }
};

Upvotes: 1

Views: 572

Answers (2)

Mohammad Ali Rony
Mohammad Ali Rony

Reputation: 4915

All Keys and values will be displays

import React, {Component} from "react";

import "./style.scss";
const dictionaryFile = require ('./../../dictionary/dictionary.json');

export default class Test extends Component {
    render() {
        return (
            <div className="test">
                {dictionaryFile.dictionary.map(elem => (
                    <div>
                    {Object.keys(elem).forEach(function(key) {
                      <p>{key}: { elem[key]}</p>
                      });}
                    </div>
                  ))
                }
            </div>
        );
    }
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

Upvotes: 0

Andus
Andus

Reputation: 1731

This renders everything in your JSON

import React, {Component} from "react";
import "./style.scss";
const dictionaryFile = require ('./../../dictionary/dictionary.json');

export default class Test extends Component {
    render() {
        return (
            <div className="test">
                {dictionaryFile.dictionary.map(elem => (
                    <div>
                       <p>{elem.index}</p>
                       <p>{elem.engwords}</p>
                       <p>{elem.ruswords}</p>
                    </div>
                  ))
                }
            </div>
        );
    }
};

Upvotes: 3

Related Questions