Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exporting/importing Json object in es6

Tags:

I am converting some ES5 code to ES6.

I have the following line somewhere in the file StatesComponent.js

const STATES = require('../data/states.js'); 

I am using jspm and it doesn't support require, so I would like to use ES6 import syntax instead.

The states.js file contains the following:

exports.AU = [     { value: 'australian-capital-territory', label: 'Australian Capital Territory', className: 'State-ACT' },     { value: 'new-south-wales', label: 'New South Wales', className: 'State-NSW' },     { value: 'victoria', label: 'Victoria', className: 'State-Vic' },  ];  exports.US = [     { value: 'AL', label: 'Alabama', disabled: true },     { value: 'AK', label: 'Alaska' },     { value: 'AS', label: 'American Samoa' }, ]; 

STATES variable is being used as var options = STATES[this.state.country];

How do I change the format of the json in states.js such that I can `import' it?

i.e import STATES from '../data/states'

like image 828
sedo023 Avatar asked Jan 12 '16 10:01

sedo023


People also ask

How do I export a JSON file?

To export package JSON first open a package, find the Import/Export dropdown and press the Export button. After that, the browser will start a download. The exported JSON file is formatted so it will be easy to track the difference between such files.


1 Answers

Not sure if you got the answer to this already but you can export it as:-

export default {   STATES: {     'AU' : {...},     'US' : {...}   } }; 

to which you can import as:-

import STATES from 'states'; 

or

var STATES = {}; STATES.AU = {...}; STATES.US = {...}; export STATES; 

to which you can import as:-

import { STATES } from 'states'; 

Notice the difference between one that uses default and one that doesn't. With default you can export any javascript expression and during import you can use whatever identifier and it will be defaulted to that default expression. You could also have done

import whatever from 'states'; 

and whatever would get the value of an object that we assigned to default.

In contrast, when you don't export default expression, export exports it as an part of object which is why you had to use

import {STATES} 

In this case you HAVE to use the right literal name for import to work or else import will not be able to understand what you're trying to import. Also, note that it's using object destructuring to import the right value.

And like @AlexanderT said, there are ways to import as * too, in fact there are various ways to import and export but I hope I explained the core concept of how this import/export works.

like image 144
shriek Avatar answered Sep 23 '22 06:09

shriek