Home > Enterprise >  Cannot display JSON objects in React
Cannot display JSON objects in React

Time:10-31

My JSON file is not being properly displayed by my React script. What am I doing wrong? Any help will be appreciated. My App.js file is like:

`

import "./App.css";
import title from "./data/breaking.json";

export default function App() {
    const { data } = title
    return (
    <div className="App">
      {data}
    </div>
  );
}

`

My JSON file is like "./data/breaking.json":

`

{
    "pubDate":{
        "5":"31-10-2022 06:26:18 UTC",
        "1":"31-10-2022 06:26:09 UTC",
        "4":"31-10-2022 06:24:07 UTC",
        "3":"31-10-2022 06:22:43 UTC",
        "8":"31-10-2022 06:21:59 UTC",
        "2":"31-10-2022 11:51:04 ",
        "7":"31-10-2022 06:20:48 UTC",
        "0":"31-10-2022 02:20:33 ",
        "9":"31-10-2022 06:20:17 UTC",
        "10":"31-10-2022 06:18:00 UTC"
    },
    "timestamp":{
        "5":1667197578.0,
        "1":1667197569.0,
        "4":1667197447.0,
        "3":1667197363.0,
        "8":1667197319.0,
        "2":1667197264.0,
        "7":1667197248.0,
        "0":1667197233.0,
        "9":1667197217.0,
        "10":1667197080.0
    }

`

I tried several solutions but none worked. I tried reformatting the JSON file, but that will be costly since the cron is already live. The JSON file gets periodically updated. So I was expecting it to render in real time on the browser.

CodePudding user response:

Destructure your title object properly. There is no data property in your imported object.

You can see the following:

import React from 'react';
import './style.css';
import data from '../data/breaking.json';

export default function App() {
  const { pubDate, timestamp } = data;

  console.log(pubDate, timestamp);

  return (
    <div>
      <h1>{ pubDate[0] }</h1>
      <h1>{ timestamp[0] }</h1>
    </div>
  );
}

https://stackblitz.com/edit/react-7zbxx7?embed=1&file=src/App.js

CodePudding user response:

You can get JSON data like the below:

const  data  = title
console.log("data==>",data.pubDate)
console.log("data==>",data.timestamp)

Where title is the JSON file imported name and it will be initialized to data and from data you can get pubDate and timestamp.

CodePudding user response:

use require to import JSON file, like

const title = require("./data/breaking.json");

Object.values

import "./App.css";
const title = require("./data/breaking.json");

export default function App() {
  const { pubDate, timestamp } = title;

  return (
    <div className="App">
      {Object.values(pubDate).map((val) => (
        <p>{val}</p>
      ))}
    </div>
  );
}
  • Related