Pulling data from local json file

I have not used json files as of yet, and I am curious on how to get the information out of it. I understand how to parse it which turns it into a javascript object, and then I can use that to populate what I need. However, all the examples I looked at they were creating a string in JavaScript and then turning that into the object.

To be more clear, it was like they were taking a line from their .json file and making it a string to parse and turn it into a object. Is there a way to get the information directly from the json file? Or, is it a common thing to take the information from the json file, creating a variable to hold that string, and then parsing it?

I’m not sure I understand your explanation of the examples you found. The best way to get answers about things is to show us the code, such as pasting it in here or giving us a link to it.

For example the person on this example said " have saved a JSON file in my local system and created a JavaScript file in order to read the JSON file and print data out. Here is the JSON file:"

data = '[{"name" : "Niroj", "age" : "22"},{"name" : "Dey", "age" : "20"}]';

Then they do this to parse it into an object

var mydata = JSON.parse(data);

So, they have a json file, but they copy it to a variable and then parse the variable. Im just thinking it would make mor sense if there was a way to get the information directly from the file and parsing it that way? Instead of copy and pasting the information in

OK, I think perhaps I found the source of your example?

How to read an external local JSON file in JavaScript?

Read the third comment below the first answer:

“This is not a correct answer. The example in the answer is not loading a json file. It is actually just loading another javascript file which stores some hardcoded json as a variable named data .”

This is exactly right. There is nothing wrong with doing this if it works for your situation. But it is not technically reading a local JSON file.

To answer your question, yes, there are other ways to read in a JSON object without storing it as a string. I think we need more detailed information on just exactly what you are trying to do. Is this a web application or are you running your JS through node? Is this a user initiated process (i.e. the user can pick the JSON file they want to load) or is this done automatically by the application?

I will do my best to explain. I have a .json file that looks like this

[
  {
    "name": "Mercury",
    "overview": {
      "content": "Mercury is the smallest planet in the Solar System and the closest to the Sun. Its orbit around the Sun takes 87.97 Earth days, the shortest of all the Sun's planets. Mercury is one of four terrestrial planets in the Solar System, and is a rocky body like Earth.",
      "source": "https://en.wikipedia.org/wiki/Mercury_(planet)"
    },
    "structure": {
      "content": "Mercury appears to have a solid silicate crust and mantle overlying a solid, iron sulfide outer core layer, a deeper liquid core layer, and a solid inner core. The planet's density is the second highest in the Solar System at 5.427 g/cm3 , only slightly less than Earth's density.",
      "source": "https://en.wikipedia.org/wiki/Mercury_(planet)#Internal_structure"
    },
    "geology": {
      "content": "Mercury's surface is similar in appearance to that of the Moon, showing extensive mare-like plains and heavy cratering, indicating that it has been geologically inactive for billions of years. It is more heterogeneous than either Mars's or the Moon’s.",
      "source": "https://en.wikipedia.org/wiki/Mercury_(planet)#Surface_geology"
    },
    "rotation": "58.6 Days",
    "revolution": "87.97 Days",
    "radius": "2,439.7 KM",
    "temperature": "430°c",
    "images": {
      "planet": "./assets/planet-mercury.svg",
      "internal": "./assets/planet-mercury-internal.svg",
      "geology": "./assets/geology-mercury.png"
    }
  },
  {
    "name": "Venus",
    "overview": {
      "content": "Venus is the second planet from the Sun. It is named after the Roman goddess of love and beauty. As the brightest natural object in Earth's night sky after the Moon, Venus can cast shadows and can be, on rare occasions, visible to the naked eye in broad daylight.",
      "source": "https://en.wikipedia.org/wiki/Venus"
    },
    "structure": {
      "content": "The similarity in size and density between Venus and Earth suggests they share a similar internal structure: a core, mantle, and crust. Like that of Earth, Venusian core is most likely at least partially liquid because the two planets have been cooling at about the same rate.",
      "source": "https://en.wikipedia.org/wiki/Venus#Internal_structure"
    },
    "geology": {
      "content": "Much of the Venusian surface appears to have been shaped by volcanic activity. Venus has several times as many volcanoes as Earth, and it has 167 large volcanoes that are over 100 km (60 mi) across. The only volcanic complex of this size on Earth is the Big Island of Hawaii.",
      "source": "https://en.wikipedia.org/wiki/Venus#Surface_geology"
    },
    "rotation": "243 Days",
    "revolution": "224.7 Days",
    "radius": "6,051.8 KM",
    "temperature": "471°c",
    "images": {
      "planet": "./assets/planet-venus.svg",
      "internal": "./assets/planet-venus-internal.svg",
      "geology": "./assets/geology-venus.png"
    }
  },
  {
    "name": "Earth",
    "overview": {
      "content": "Third planet from the Sun and the only known planet to harbor life. About 29.2% of Earth's surface is land with remaining 70.8% is covered with water. Earth's distance from the Sun, physical properties and geological history have allowed life to evolve and thrive.",
      "source": "https://en.wikipedia.org/wiki/Earth"
    },
    "structure": {
      "content": "Earth's interior, like that of the other terrestrial planets, is divided into layers by their chemical or physical (rheological) properties. The outer layer is a chemically distinct silicate solid crust, which is underlain by a highly viscous solid mantle.",
      "source": "https://en.wikipedia.org/wiki/Earth#Internal_structure"
    },
    "geology": {
      "content": "The total surface area of Earth is about 510 million km2. The continental crust consists of lower density material such as the igneous rocks granite and andesite. Less common is basalt, a denser volcanic rock that is the primary constituent of the ocean floors.",
      "source": "https://en.wikipedia.org/wiki/Earth#Surface"
    },
    "rotation": "0.99 Days",
    "revolution": "365.26 Days",
    "radius": "6,371 KM",
    "temperature": "16°c",
    "images": {
      "planet": "./assets/planet-earth.svg",
      "internal": "./assets/planet-earth-internal.svg",
      "geology": "./assets/geology-earth.png"
    }
  },
  {
    "name": "Mars",
    "overview": {
      "content": "Mars is the fourth planet from the Sun and the second-smallest planet in the Solar System, being larger than only Mercury. In English, Mars carries the name of the Roman god of war and is often referred to as the \"Red Planet\".",
      "source": "https://en.wikipedia.org/wiki/Mars"
    },
    "structure": {
      "content": "Like Earth, Mars has differentiated into a dense metallic core overlaid by less dense materials. Scientists initially determined that the core is at least partially liquid. Current models of its interior imply a core consisting primarily of iron and nickel with about 16–17% sulfur.",
      "source": "https://en.wikipedia.org/wiki/Mars#Internal_structure"
    },
    "geology": {
      "content": "Mars is a terrestrial planet whose surface consists of minerals containing silicon and oxygen, metals, and other elements that typically make up rock. The surface is primarily composed of tholeiitic basalt, although parts are more silica-rich than typical basalt.",
      "source": "https://en.wikipedia.org/wiki/Mars#Surface_geology"
    },
    "rotation": "1.03 Days",
    "revolution": "1.88 Years",
    "radius": "3,389.5 KM",
    "temperature": "-28°c",
    "images": {
      "planet": "./assets/planet-mars.svg",
      "internal": "./assets/planet-mars-internal.svg",
      "geology": "./assets/geology-mars.png"
    }
  },
  {
    "name": "Jupiter",
    "overview": {
      "content": "Jupiter is the fifth planet from the Sun and the largest in the Solar System. It is a gas giant with a mass two and a half times that of all the other planets in the Solar System combined, but less than one-thousandth the mass of the Sun.",
      "source": "https://en.wikipedia.org/wiki/Jupiter"
    },
    "structure": {
      "content": "When the Juno arrived in 2016, it found that Jupiter has a very diffuse core that mixes into its mantle. A possible cause is an impact from a planet of about ten Earth masses a few million years after Jupiter's formation, which would have disrupted an originally solid Jovian core.",
      "source": "https://en.wikipedia.org/wiki/Jupiter#Internal_structure"
    },
    "geology": {
      "content": "The best known feature of Jupiter is the Great Red Spot, a persistent anticyclonic storm located 22° south of the equator. It is known to have existed since at least 1831, and possibly since 1665.",
      "source": "https://en.wikipedia.org/wiki/Jupiter#Great_Red_Spot_and_other_vortices"
    },
    "rotation": "9.93 Hours",
    "revolution": "11.86 Years",
    "radius": "69,911 KM",
    "temperature": "-108°c",
    "images": {
      "planet": "./assets/planet-jupiter.svg",
      "internal": "./assets/planet-jupiter-internal.svg",
      "geology": "./assets/geology-jupiter.png"
    }
  },
  {
    "name": "Saturn",
    "overview": {
      "content": "Saturn is the sixth planet from the Sun and the second-largest in the Solar System, after Jupiter. It is a gas giant with an average radius of about nine and a half times that of Earth. It only has one-eighth the average density of Earth.",
      "source": "https://en.wikipedia.org/wiki/Saturn"
    },
    "structure": {
      "content": "Despite consisting mostly of hydrogen and helium, most of Saturn's mass is not in the gas phase, because hydrogen becomes a non-ideal liquid when the density is above 0.01 g/cm3, which is reached at a radius containing 99.9% of Saturn's mass.",
      "source": "https://en.wikipedia.org/wiki/Saturn#Internal_structure"
    },
    "geology": {
      "content": "The outer atmosphere of Saturn contains 96.3% molecular hydrogen and 3.25% helium by volume. The planet's most famous feature is its prominent ring system, which is composed mostly of ice particles with a smaller amount of rocky debris and dust.",
      "source": "https://en.wikipedia.org/wiki/Saturn#Atmosphere"
    },
    "rotation": "10.8 Hours",
    "revolution": "29.46 Years",
    "radius": "58,232 KM",
    "temperature": "-138°c",
    "images": {
      "planet": "./assets/planet-saturn.svg",
      "internal": "./assets/planet-saturn-internal.svg",
      "geology": "./assets/geology-saturn.png"
    }
  },
  {
    "name": "Uranus",
    "overview": {
      "content": "Uranus is the seventh planet from the Sun. Its name is a reference to the Greek god of the sky, Uranus according to Greek mythology, was the great-grandfather of Ares. It has the third-largest planetary radius and fourth-largest planetary mass in the Solar System.",
      "source": "https://en.wikipedia.org/wiki/Uranus"
    },
    "structure": {
      "content": "The standard model of Uranus's structure is that it consists of three layers: a rocky (silicate/iron–nickel) core in the centre, an icy mantle in the middle and an outer gaseous hydrogen/helium envelope. The core is relatively small, with a mass of only 0.55 Earth masses.",
      "source": "https://en.wikipedia.org/wiki/Uranus#Internal_structure"
    },
    "geology": {
      "content": "The composition of Uranus's atmosphere is different from its bulk, consisting mainly of molecular hydrogen and helium. The helium molar fraction, i.e. the number of helium atoms per molecule of gas, is 0.15±0.03 in the upper troposphere.",
      "source": "https://en.wikipedia.org/wiki/Uranus#Atmosphere"
    },
    "rotation": "17.2 Hours",
    "revolution": "84 Years",
    "radius": "25,362 KM",
    "temperature": "-195°c",
    "images": {
      "planet": "./assets/planet-uranus.svg",
      "internal": "./assets/planet-uranus-internal.svg",
      "geology": "./assets/geology-uranus.png"
    }
  },
  {
    "name": "Neptune",
    "overview": {
      "content": "Neptune is the eighth and farthest-known Solar planet from the Sun. In the Solar System, it is the fourth-largest planet by diameter, the third-most-massive planet, and the densest giant planet. It is 17 times the mass of Earth, more massive than its near-twin Uranus.",
      "source": "https://en.wikipedia.org/wiki/Neptune"
    },
    "structure": {
      "content": "Neptune's internal structure resembles that of Uranus. Its atmosphere forms about 5% to 10% of its mass and extends perhaps 10% to 20% of the way towards the core. Increasing concentrations of methane, ammonia and water are found in the lower regions.",
      "source": "https://en.wikipedia.org/wiki/Neptune#Internal_structure"
    },
    "geology": {
      "content": "Neptune's atmosphere is 80% hydrogen and 19% helium. A trace amount of methane is also present. Prominent absorption bands of methane exist at wavelengths above 600 nm, in the red and infrared portion of the spectrum.",
      "source": "https://en.wikipedia.org/wiki/Neptune#Atmosphere"
    },
    "rotation": "16.08 Hours",
    "revolution": "164.79 Years",
    "radius": "24,622 KM",
    "temperature": "-201°c",
    "images": {
      "planet": "./assets/planet-neptune.svg",
      "internal": "./assets/planet-neptune-internal.svg",
      "geology": "./assets/geology-neptune.png"
    }
  }
]

I am attempting to do the challenge

You can see there are three buttons on each page, and I am assuming that for each button clicked there is specific information from the json file that get displayed. I do not have any code for it yet as I am trying to get through the thought process first.

I looked some more, and it looks like I will have to use the fetch api. I guess I will need to figure out how to put my code on a server to do this?

fetch is definitely one way to do this. As long as the json file is publicly available on a web server then you can fetch it and read the contents into a variable. But this may not be the only alternative. Are you going to use a framework to build this app? Or are you sticking to purely vanilla JS?

Just normal javascript.

Are you allowed to change the json file? A relatively easy way to import this data would be to add an export statement at the beginning of the json file:

export const planets =

Then you could import it into your main JS file:

import { planets } from './planets.js';

And planets would hold the array of planet information defined in the json file.

To use this method, make sure to add type="module" to the <script> for the JS file that is doing the import. Also, you have to serve the html page through a web server, you can’t just open the file in your browser through the local file system. But this is also the case if you use fetch.

1 Like

I don’t see why not. As long as I am not copying some ones code, and trying to use it as my own it should be fine. They encourage to try new ways to get things done.

I found a live server extension for visual studio code when I was looking at the fetch.

Just making sure I am on the same page. That would be the main page for each planet correct. For example. I would have an earth.js, mercury.js, and so on so it would look like

<script type="module" src="mercury.js"></script>

Yep. If the JS file needs access to the JSON data and you want to use import technique above, then the <script> tag must include type="module".

2 Likes

Thanks! I will start on it tomorrow. Appreciate all the help

So, the json file does not like the line

export const planets =

it gives me the error “Expected a JSON object, array or literal.json” on export

That’s not JSON, so no, it will not like it. JSON isn’t a programming language and doesn’t know anything about JavaScript, it’s just way of transferring data by writing it in a very specific format. The contents of a JSON file have to be JSON.


Note that following will work in Chrome (was enabled by default in December), will work everywhere soonish (normal caveat, uses ES modules, script tag in HTML file must have the type attribute set to “module”, has to be run on a server, won’t work by just opening the HTML file in a browser)

import planets from "./planets.json" assert { type: "json" };

console.log(planets[0].name)
// Logs "Mercury"
2 Likes

Awesome! Got it working

1 Like