Can't import JSON in react - javascript

I'm having what I'm sure it's a stupid problem but I can't seem to find a way around it.
I have a react application and I'm trying to import a JSON file. Here it is:
{
"words":{
"ita":[
"ora",
"via",
"dio",
"sud",
"don",
"zia"
]
}
}
And here's the react code:
import React, { Component} from 'react'
import words from 'Assets/Words.json'
console.log(words)
console.log(words.ita)
export default class WordsGen extends Component {
...
The two console.log print, respectively:
{words: {…}}
words:
ita: (6) ["ora", "via", "dio", "sud", "don", "zia"]
__proto__: Object
__proto__: Object
and undefined.
I'm using the json file to put more languages in the app, but I can't understand why when I print just words I can see the property ita inside, and when I try to print words.ita or words["ita"] I get undefined.
What am I missing?

Should be:
words.words.ita
You are importing as "words" and then the object has a words object. It might be more clear to change the import name:
import MyJson from 'my.json';
console.log(MyJson.words.ita)

Because your imported object words contains whole json. When you write
import words from 'Assets/Words.json';
it will become
words = {
words:{
ita:[
"ora",
"via",
"dio",
"sud",
"don",
"zia"
]
}
}
That's why your object words doesn't really have property ita. That's why it will return undefined.
You need to write words.words.ita. For better code-style:
/// words.json
{
"ita":[
"ora",
"via",
"dio",
"sud",
"don",
"zia"
]
}
import words from 'Assets/Words.json';
words.ita // then your code
/// or even better with new es6 destructing
import {ita = []} from 'Assets/Words.json';
ita // do anything that you want

Related

Displaying json arrays in React

I'm using React to display data,and I want to display data inside hits, which is array of recipes.Below is the structure. I want to list the properties inside each recipe.
recipe": {
"uri": "http://www.edamam.com/ontologies/edamam.owl#recipe_d090689494d5bc05e53e4a808bf6db1c",
"label": "Recipe For (A Kind Of) Pisto, With Rice And Eggs",
"image": "https://edamam-product-images.s3.amazonaws.com/web-img/b7c/b7c8284b065e055f74c59f3f88718b84.jpg?X-Amz-Security-Token=IQoJb3JpZ2luX2VjEPH%2F%2F%2F%2F%2F%2F%2F%2F%2F%2FwEaCXVzLWVhc3QtMSJIMEYCIQDpnaXhSzGfXCmxvypbyEuHsQoaEVX9tsSxAHEAttR%2FuAIhAI%2Bso6mALweGSGbfFqjijfLZYKlNjx9vofk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ebOajGpQA0QTV1m4z3HijmRicL2LLW4q5RooyF2oR5QKBu8%2Fk&X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Date=20221126T013542Z&X-Amz-SignedHeaders=host&X-Amz-Expires=3600&X-Amz-Credential=ASIASXCYXIIFP4CCVRCC%2F20221126%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Signature=68656c34e850742a7b45117e905bbb71babec459015201e4246e65a5d6946d3b",
"source": "Mostly Eating",
"url": "http://www.mostlyeating.com/in-praise-of-pisto-and-a-perfectly-balanced-meal",
"shareAs": "http://www.edamam.com/recipe/recipe-for-a-kind-of-pisto-with-rice-and-eggs-d090689494d5bc05e53e4a808bf6db1c/tomato%2Cegg%2Cspinach",
"yield": 2.0,
"dietLabels": [
"Balanced",
"High-Fiber"
],
"healthLabels": [
"Vegetarian",
"Pescatarian",
"Dairy-Free",
"Gluten-Free",
"Wheat-Free",
"Peanut-Free",
"Tree-Nut-Free",
"Soy-Free",
"Fish-Free",
"Shellfish-Free",
"Pork-Free",
"Red-Meat-Free",
"Crustacean-Free",
"Celery-Free",
"Mustard-Free",
"Sesame-Free",
"Lupine-Free",
"Mollusk-Free",
"Alcohol-Free",
"Kosher"
],
"cautions": [ ]
}
Here is my code.
import React, { Component } from 'react';
import axios from 'axios'
import CallAPI from './CallAPI';
const api = 'http://localhost:5000' // backend address
class GetRecipe extends Component{
constructor(props){
super(props)
this.state={
list:[]
}
this.setState=this.setState.bind(this)
}
getData=()=>{
var url = `${api}/getRecipe`;
axios.get(url)
.then(response=>{
console.log(response.data)
this.setState({list:response.hits})
}).catch(err=>console.log(err))
}
render(){
return(
<div>
<h2>Get Recipe</h2>
<button onClick={this.getData}>Get</button>
<p>{this.state.list}</p>
</div>
)
}
}
export default GetRecipe;
Using the above code, there is no error, but nothing display in the page. So I tried another way:
<ul>
{this.state.list.map((value, key)=>{
return<li key={key}>{value}</li>
})}
</ul>
However, in this way I got error
getRecipe.js:37 Uncaught TypeError: Cannot read properties of undefined (reading 'map')
at GetRecipe.render (getRecipe.js:37:1)
I also try to change the getData function, then I got TypeError: Cannot read properties of undefined (reading 'setState').
getData(){
axios.get(`${api}/getRecipe`)
.then((response)=>{
this.setState({list:response.data})
})
.catch(function (error){
console.log(error)
})
}
I try this way of displaying dat before, but I don't know why it doesn't work this time. How can i make it work ?
In your first try, you have this line:
this.setState({list:response.hits})
This should (probably) be:
this.setState({list:response.data.hits})
This resolves your (first) TypeError.
Then you try to render it like this:
<p>{this.state.list}</p>
What is React supposed to do with this? It won't magically create HTML elements for your array.
Mapping over the array is the correct way to render an element per item in the array. But:
return<li key={key}>{value}</li>
value is a plain object. How is React supposed to render it? And consider using a real key, not just the array index.
Your change of getData() makes it forget this. You probably meant to bind it in the constructor instead of setState(). This resolves your second TypeError. Or change it back to an arrow function.

React-Image-Annotate - SyntaxError: Cannot use import statement outside a module

I'm trying to use react-image-annotate but it's giving me this issue when I first try to set it up.
And here's how I'm using it:
import React from 'react'
import ReactImageAnnotate from 'react-image-annotate'
function ImageAnnotator() {
return (
<ReactImageAnnotate
selectedImage="https://images.unsplash.com/photo-1561518776-e76a5e48f731?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=750&q=80"
// taskDescription="# Draw region around each face\n\nInclude chin and hair."
// images={[
// { src: 'https://example.com/image1.png', name: 'Image 1' },
// ]}
// regionClsList={['Man Face', 'Woman Face']}
/>
)
}
export default ImageAnnotator
I'm using Next.js if that matters
UPDATE 1
I tried using this babel plugin as suggested by Alejandro Vales. It gives the same error as before. Here's the babel key in my package.json:
"babel": {
"presets": [
"next/babel"
],
"plugins": [
[
"#babel/plugin-proposal-decorators",
{
"legacy": true
}
],
[
"#babel/plugin-transform-modules-commonjs",
{
"allowTopLevelThis": true
}
]
]
}
I would say that the issue relies in the library itself by what they replied in here (similar bug) https://github.com/UniversalDataTool/react-image-annotate/issues/90#issuecomment-683221311
Indeed one way to fix it I would say is adding babel to the project so you can transform the imports in your project to require automatically without having to change the code on your whole project.
This is the babel package you are looking for https://babeljs.io/docs/en/babel-plugin-transform-modules-commonjs
Another reason for this could be an outdated version of your package, as some people report to have this fixed after using a newer version of Create React App (https://github.com/UniversalDataTool/react-image-annotate/issues/37#issuecomment-607372287)
Another fix you could do (a little crazier depending on your resources) is forking the library, creating a CJS version of the lib, and then pushing that to the library, so you and anybody else can use that in the future.
I got a tricky solution!
Problem is that react-image-annotate can only be imported in client-side(SSR got error for import keyword)
So, let react-image-annotate in Nextjs be imported only in client side
(https://nextjs.org/docs/advanced-features/dynamic-import#with-no-ssr)
in Next Page that needs this component, You can make component like this
import dynamic from "next/dynamic";
const DynamicComponentWithNoSSR = dynamic(() => import("src/components/Upload/Annotation"), { ssr: false });
import { NextPage } from "next";
const Page: NextPage = () => {
return (
<>
<DynamicComponentWithNoSSR />
</>
);
};
export default Page;
Make component like this
//#ts-ignore
import ReactImageAnnotate from "react-image-annotate";
import React from "react";
const Annotation = () => {
return (
<ReactImageAnnotate
labelImages
regionClsList={["Alpha", "Beta", "Charlie", "Delta"]}
regionTagList={["tag1", "tag2", "tag3"]}
images={[
{
src: "https://placekitten.com/408/287",
name: "Image 1",
regions: [],
},
]}
/>
);
};
export default Annotation;

Trying to display random data from a local json file I created, but getting an undefined error in render

I am learning React and right now I am trying to get my app to display a random joke (both question and answer) from the JSON file I created. However, I get the following error: getRandomJoke is not defined. I figured since it's a function, getRandomJoke does not need to get defined. Can someone explain where my mistake is and why I am getting this error?
This is the local JSON file I created:
SportsJokesData.js
const SportsJokesData = [
{
id: "1",
question: "What did the baseball glove say to the ball?",
answer: "Catch ya later!"
},
{
id: "2",
question: "What are the rules for zebra baseball?",
answer: "Three stripes and you’re out."
},
{
id: "3",
question: "Why are umpires always overweight?",
answer: "It’s their job to clean their plates."
}
export default SportsJokesData;
This is the component I created to get it displayed on my browser, SportsJokesApi.JS:
import React from 'react'
import SportsJokesData from './SportsJokesData';
class SportsJokesApi extends React.Component {
getRandomJoke(){
return SportsJokesData[(SportsJokesData.length * Math.random()) << 0]
}
render() {
return (
<p>{getRandomJoke}</p>
)
}
}
export default SportsJokesApi;
Do <p>{this.getRandomJoke()}</p> inside your render()

How to access Object array file into react component?

I am trying to access an object array file within src folder eg: data.js(Object array only) this file into my app.js(react component)
in first scenario 1.I have tried this problem using react in
src--[app.js(component)/data.js(object array)].
When I was run it shows me an error like
(TypeError: _data__WEBPACK_IMPORTED_MODULE_1___default.a.map is not a function)means null array/undefined.
in second scenarios 2. when I add object array in app.js within the same page its shows me perfect result. without an error but trying from another file like data.js it taking null array I have used to stringify() and JSON parser but no result
Object array file data.js ->
const datas=[
{
"id":"1",
"firstname":"sam",
"lastname":"parkar"
},
{
"id":"2",
"firstname":"julee",
"lastname":"fransic"
}
];
react component app.js ->
import React from 'react';
import datas from './data';
import DataInfo from './DataInfo';
function App () {
const appdata=datas.map( inner => inner.id + inner.firstname + inner.lastname)
//print on console
console.log(appdata)
return (
<div className="App">
<p>App js page</p>
{appdata}
</div>
)
}
export default App;
error ->
TypeError: _data__WEBPACK_IMPORTED_MODULE_1___default.a.map is not a function
21 | return (
22 |
23 |
> 24 | <div className="App">
| ^ 25 |
26 | <p>App js page</p>
actual result:-
App js page
1samparkar2juleefransic
and on console
(2) ["1samparkar", "2juleefransic"]
0: "1samparkar"
1: "2juleefransic"
Make sure you export the datas correctly
export const datas=[
{
"id": "1",
"firstname": "sam",
"lastname": "parkar"
},
{
"id": "2",
"firstname": "julee",
"lastname": "fransic"
}
];
And in app.js call it like this:
import {datas} from './data';
You can use JSON file like this:
datas.json
[
{
"id":"1",
"firstname":"sam",
"lastname":"parkar"
},
{
"id":"2",
"firstname":"julee",
"lastname":"fransic"
}
]
In app.js:
import datas from './datas.json';
If you are using JSON file then save that file as datas.json
Now in your app.js file use <datas/> instead of {datas}.
you can use {datas} when you are using it in a jsx attribute. for example-
<textarea name="JSON" value={datas} />.
but in your case, you should use <datas />.

Exporting/importing Json object in es6

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'
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.

Categories