I'm making an app using React JS. It's basically supposed to get JSON content and display it in the screen. I know this is supposed to be something really simple, but I am just unable to implement it. Please look into my code and show a way to import and display this JSON in my React. Thanks!!
JSON
[
{
"id": "1",
"title": "Test",
"firstName": "Testing",
"lastName": "Thingy",
"salary": 5000
},
{
"id": "2",
"title": "Test",
"firstName": "Test",
"lastName": "Thing",
"salary": 6000
}
]
React JS code in a minimal reproducible example -
import thing from "./card.json";
const item = JSON.stringify(thing[0][1]);
const item2 = JSON.stringify(thing[1]);
const ProductCard = ({ data }) => {
return (
<div>
<h1>{item}</h1>
<h1>{item2}</h1>
</div>
);
};
export default ProductCard;
CodePudding user response:
Hey the above format of JSON is object inside a array so we can access the array elemnet using things[0] but for for object we need to provide the key. In above you don't need to Stringify the JSON.
import thing from "./card.json";
const item = thing[0].id;
const item2 = thing[1].title;
const ProductCard = ({ data }) => {
return (
<div>
<h1>{item}</h1>
<h1>{item2}</h1>
</div>
);
};
export default ProductCard;
CodePudding user response:
If all the objects in JSON is the same you can use the map
function.
It could look something like.
import thing from "./card.json";
const ProductCard = ({ data }) => {
return (
<div>
{data.map(jsonObject => {
return(
<div>
<h1>{jsonObject.title}</h1>
<p>{jsonObject.id}</p>
<p>{jsonObject.firstName}</p>
<p>{jsonObject.lastName}</p>
<p>{jsonObject.salary}</p>
</div>
)
})
}
</div>
);
};
export default ProductCard;
CodePudding user response:
if you wants to get value of one field use this code:
const item = data[0].id;
but if you wants to read all object as string use this sample:
const item2 = JSON.stringify(data[1]);