React import json data

1.5k views Asked by At

I draw a graph by using react vega. When i write config for the graph it works. I would like to get config in json format from an external file barChartConfig.json

I try to import this file but did not work. My question is how can i import a json and assign it into a variable?

import config from './barChartConfig.json';

const barSpec = config;
const Vega = ReactVega.default;

class App extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            spec: barSpec
            // ,data: barData
        };
    }

    render() {
        return (
            <div>

                <Vega spec={this.state.spec} />

            </div>
        );
    }
}

const app = document.getElementById('app');

ReactDOM.render(<App />, app);
2

There are 2 answers

0
Rohith Murali On

If you are using create-react-app, json-loader will be already included. In that case you can use the following statement to load json file.

var config = require('./barChartConfig.json');
0
Sagiv b.g On

When you use this: import config from './barChartConfig.json'; it means you are "asking" your bundler (webpack?) to include the data of this file when it creates the bundle.js file.
Of course you will need an appropriate loader for that like json-loader.
If you are trying to get this data on run time then you will need to get it via ajax request. (fetch, axios etc...)