0

Script.js and test.json are located in the 'public' folder. I need to display data from test.json in the html page. script.js:

$(document).ready(function() {

  let qqq = 'test.json';
  let www = JSON.parse(qqq);
  document.getElementById("eee").innerHTML = www;
});

server.js:

var express = require("express");
var path = require("path");
var app = express();
app.get("/", function(req, res) {
  res.sendFile(__dirname + "/views/index.html");
});

app.use(express.static(path.join(__dirname, "public")));
app.listen(8008);
console.log("Server has started!");

index.html:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" /> <title>Report</title>
    <link  rel="stylesheet" href="style.css">
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"
></script>
  <script src="script.js"></script>   
</head>
<body>
  <div class="red" id="eee"></div>
</body>
</html>

test.json:

{"tests": [
   { "testName": "testname1",
     "value": "test_value",},
   { "testName": "testname2",
     "value": "test_value",}
  ] }
  • 5
    JSON.parse() parses a json string, and not a json file .... u want to use jQuery.getJSON: https://api.jquery.com/jQuery.getJSON/ – Mischa Jan 03 '20 at 11:53
  • What **exactly** is not working with the given code? What have you tried to solve the problem? – Nico Haase Jan 03 '20 at 11:55
  • Does this answer your question? [How to get JSON from URL in JavaScript?](https://stackoverflow.com/questions/12460378/how-to-get-json-from-url-in-javascript) – Dan O Jan 03 '20 at 13:19

1 Answers1

2
let qqq = 'test.json';  //you are parsing test.json string.

you can use ajax to get data from json file as following

$.ajax({
    type: "Get",
    url: "test.json",
    dataType: "json",
    success: function(data) {
          let www = JSON.parse(data);
          $("#eee").html(www);
    },
    error: function(){
        alert("json not found");
    }
});
Ritesh Dhoke
  • 169
  • 10
  • $(document).ready(function() { $.ajax({ type: "Get", url: "testReport.json", dataType: "json", success: function(data) { let www = JSON.parse(data); /* Error: Unexpected token o in JSON */ $("#timenow").html(www); }, error: function() { alert("json not found"); } }); }); @Ritesh Dhoke, Don't work - There is Unexpected token o in JSON – Александр Jan 03 '20 at 13:07
  • 1
    test.json data is not in json format, you need to make some changes {"tests": [ { "testName": "testname1", "value": "test_value"}, { "testName": "testname2", "value": "test_value"} ] } – Ritesh Dhoke Jan 04 '20 at 03:43