I would like to import a JSON5 file into a Javascript object in the same way [one can import a JSON file](import config from '../config.json').
Shows this message on hovering but it's clearly there
Cannot find module '../conf/config.json5' or its corresponding type declarations.ts(2307)
I have 2 side questions related to the main one above:
Will I get intelisense for contents inside .json5, like regular json
Does it even work like it works with require()? Do I have to use import() instead of regular import ?
You will need the package to do so: json5.
There are one of two ways we can use this:
One: (target module system is CommonJS) require it
Following the README, we register json5:
import "json5/lib/register";
Then you can use require to import it:
const config = require("../config/config.json5");
Two: Reading the file and then using json5 to parse it:
import json5 from "json5";
import { readFile } from "fs/promises";
(async () => {
const text = await fs.readFile("./path/to/config.json5"); // path to config.json5 from entry point
const config = json5.parse(text);
})();
You can also use the provided CLI to convert json5 files to regular json that you can use.
The creator updated the json5 wiki
Wiki
You need to create an extra file with .d.ts extension to support intellisense.
In my standard React app, I need to achieve the following: import a file that sits within my src folder, in order to simply read its content as a string. For example, let's say I have the following code in a file:
alert('hey')
then in some other file, I would like to do something like this, in pseudo code:
import * as string from './someFile.js'
console.log(string)
The output of the console.log should be the JS code, as a string:
alert('hey')
If I could place the file within my public folder, I'd be able to perform an http request and read it as I wish. But the problem is of course, that the file is part of the build process(inside the src folder)
Can this be done?
i can think about:
define constants.js file with following code:
export default "alert('vasia')";
import this file from some react file:
import vasia from "./constants";
const App = () => {
console.log(eval(vasia));
}
is that what you r searching for?
But, must warn you: "eval" is evil!
I wanted to do the very same thing but unfortunately found out it is not possible in pure JS as at 2022.
There's a stage 3 TC39 proposal for Import Assertions which is available in Chromium-based browsers but only allows to import JSON files so it certainly would not help in this particular case.
I believe your best bet for now is to use Fetch API to get the content of your file asynchronously.
async function getSampleText() {
const response = await fetch('someFile.js');
console.log(
await response.text()
);
}
I have this function to write a unit test, I have a .json file on the same folder to be passed as a parameter but how can I pass it as a parameter?
export const getColumnsFromJsonFile = async (file) => {
if (file?.type === 'application/json') {
const result = await new window.Response(file).json()
return Object.keys(result)
}
}
./test.json is just text, what I have to do to transform in a readable file by Response?
expect(await getColumnsFromJsonFile('./test.json')).toEqual([...])
Mock import of JSON file, You can either use moduleNameMapper in your jest settings to point the import to an mocked json file.
{ "moduleNameMapper": { "setting.json": Add jest-json to your Jest config: { " setupTestFrameworkScriptFile " : " jest-json " } Or if you're already using another test framework, create a setup file and require each of them:
How to import JSON file on Jest tests?, { something } from "../my-json.json"; How can I import the JSON file on Jest Note that myJSON is already an object, no need to use JSON.parse. Answer. Example 2: Python read JSON file. You can use json.load() method to read a file containing JSON object.. Suppose, you have a file named person.json which contains a JSON object.
I have a vanilla js project that I am building with parcel. In project I have a directory with a lot of json files that I would like to use in one of my modules. I have tried to import them like I would import js files but that didn't work.
import * as regions from './Polygons'
How could I import all the files and iterate over them like you would iterate over an array of objects?
import only works if the thing you are importing is an ES6 module. Just use require in a try-catch:
import fs
dir = './Polygons'
allFiles = fs.readdirSync(dir).map (filename) ->
try
json = require(dir + '/' + filename)
catch e
error = e
return { filename, json, error }
I'm new to React and I'm trying to import a JSON DATA variable from an external file. I'm getting the following error:
Cannot find module "./customData.json"
Could some one help me? It works if I have my DATA variable in index.js but not when it's in an external JSON file.
index.js
import React, {Component} from 'react';
import ReactDOM from 'react-dom';
import customData from './customData.json';
import Profile from './components/profile';
import Hobbies from './components/hobbies';
class App extends Component {
render() {
return (
<div>
<Profile name={this.props.profileData.name}imgUrl={this.props.profileData.imgURL} />
<Hobbies hobbyList={this.props.profileData.hobbyList}/>
</div>
);
}
}
ReactDOM.render(<App profileData={DATA}/>, document.querySelector('.container'));
hobbies.js
import React, {Component} from 'react';
var Hobbies = React.createClass({
render: function(){
var hobbies = this.props.hobbyList.map(function(hobby, index){
return (<li key={index}>{hobby}</li>);
});
return (
<div>
<h5>My hobbies:</h5>
<ul>
{hobbies}
</ul>
</div>
);
}
});
export default Hobbies;
profile.js
import React from 'react';
var Profile = React.createClass({
render: function(){
return (
<div>
<h3>{this.props.name}</h3>
<img src={this.props.imgUrl} />
</div>
)
}
});
export default Profile
customData.json
var DATA = {
name: 'John Smith',
imgURL: 'http://lorempixel.com/100/100/',
hobbyList: ['coding', 'writing', 'skiing']
}
export default DATA
One nice way (without adding a fake .js extension which is for code not for data and configs) is to use json-loader module. If you have used create-react-app to scaffold your project, the module is already included, you just need to import your json:
import Profile from './components/profile';
This answer explains more.
This old chestnut...
In short, you should be using require and letting node handle the parsing as part of the require call, not outsourcing it to a 3rd party module. You should also be taking care that your configs are bulletproof, which means you should check the returned data carefully.
But for brevity's sake, consider the following example:
For Example, let's say I have a config file 'admins.json' in the root of my app containing the following:
admins.json
[{
"userName": "tech1337",
"passSalted": "xxxxxxxxxxxx"
}]
Note the quoted keys, "userName", "passSalted"!
I can do the following and get the data out of the file with ease.
let admins = require('~/app/admins.json');
console.log(admins[0].userName);
Now the data is in and can be used as a regular (or array of) object.
With json-loader installed, you can use
import customData from '../customData.json';
or also, even more simply
import customData from '../customData';
To install json-loader
npm install --save-dev json-loader
Simplest approach is following
// Save this as someJson.js
const someJson = {
name: 'Name',
age: 20
}
export default someJson
then
import someJson from './someJson'
React 17 created from create-react-app, importing json just work by default.
import config from './config.json'
The solution that worked for me is that:-
I moved my data.json file from src to public directory.
Then used fetch API to fetch the file
fetch('./data.json').then(response => {
console.log(response);
return response.json();
}).then(data => {
// Work with JSON data here
console.log(data);
}).catch(err => {
// Do something for an error here
console.log("Error Reading data " + err);
});
The problem was that after compiling react app the fetch request looks for the file at URL "http://localhost:3000/data.json" which is actually the public directory of my react app. But unfortunately while compiling react app data.json file is not moved from src to public directory. So we have to explicitly move data.json file from src to public directory.
Please store your JSON file with the .js extension and make sure that your JSON should be in same directory.
// rename the .json file to .js and keep in src folder
Declare the json object as a variable
var customData = {
"key":"value"
};
Export it using module.exports
module.exports = customData;
From the component that needs it, make sure to back out two folders deep
import customData from '../customData';
In current react build you simply import and use:
import jsonData from 'path/to/myJson.json'
try with export default DATA or module.exports = DATA
there are multiple ways to do this without using any third-party code or libraries (the recommended way).
1st STATIC WAY: create a .json file then import it in your react component example
my file name is "example.json"
{"example" : "my text"}
the example key inside the example.json can be anything just keep in mind to use double quotes to prevent future issues.
How to import in react component
import myJson from "jsonlocation";
and you can use it anywhere like this
myJson.example
now there are a few things to consider. With this method, you are forced to declare your import at the top of the page and cannot dynamically import anything.
Now, what about if we want to dynamically import the JSON data? example a multi-language support website?
2 DYNAMIC WAY
1st declare your JSON file exactly like my example above
but this time we are importing the data differently.
let language = require('./en.json');
this can access the same way.
but wait where is the dynamic load?
here is how to load the JSON dynamically
let language = require(`./${variable}.json`);
now make sure all your JSON files are within the same directory
here you can use the JSON the same way as the first example
myJson.example
what changed? the way we import because it is the only thing we really need.
I hope this helps.
var langs={
ar_AR:require('./locale/ar_AR.json'),
cs_CZ:require('./locale/cs_CZ.json'),
de_DE:require('./locale/de_DE.json'),
el_GR:require('./locale/el_GR.json'),
en_GB:require('./locale/en_GB.json'),
es_ES:require('./locale/es_ES.json'),
fr_FR:require('./locale/fr_FR.json'),
hu_HU:require('./locale/hu_HU.json')
}
module.exports=langs;
Require it in your module:
let langs=require('./languages');
regards
This worked well in React 16.11.0
// in customData.js
export const customData = {
//json data here
name: 'John Smith',
imgURL: 'http://lorempixel.com/100/100/',
hobbyList: ['coding', 'writing', 'skiing']
}
// in index.js
import { customData } from './customData';
// example usage later in index.js
<p>{customData.name}</p>
My friends, if you are using React and TypeScript, just do these steps and DONE!
In the tsconfig.json add these 2 new lines:
// tsconfig.json
{
"compilerOptions": {
// ... other options
"esModuleInterop": true,
"resolveJsonModule": true
}
}
Import your json:
import yourJSON from "./data/yourJSON.json"
Something that worked for me was to simply place the JSON file in the public folder. You can simply import in any js using
brain.loadData("exampleFile.json");
It is as simple as that I guess. Definitely worth a try :D