简体   繁体   中英

How can I read JSON file and generate dynamic page using jQuery based on JSON

i am new to this node and json things and I have someproblems getting data out of JSON. This is my code

'use strict';

const fs = require('fs');

let questsRawData = fs.readFileSync('quests-db.json');
let quests = JSON.parse(questsRawData);

for (var i = 0; i < quests.length; i++) {
  console.log(quests[i].title);
}

when i run this in node I am getting results as expected in terminal but in browser I am getting this msg in console

Uncaught SyntaxError: Unexpected end of JSON input
    at JSON.parse (<anonymous>)
    at showNeg.js:241
    at XMLHttpRequest.onDefaultReadyStateChangeHandler (showNeg.js:311)

also if i try to append results with jQuery to the DOM like this

for (var i = 0; i < quests.length; i++) {
  $(body).append('<p>' + quests[i].title + '</p>);
}

I am getting this error in terminal

C:\Users\Denis\Desktop\Test\main.js:9
  $(body).append('<p>' + quests[i].title + '</p>');
  ^

ReferenceError: $ is not defined

I am trying make desktop application with electron and I was thinking to use JSON as local db.

Thank you

Please install your jquery as dependency

npm install --save jquery

And then at your index.html add this script.

  <head>
    <script>
      window.$ = window.jQuery = require("jquery");
    </script>
    ....

And createBrowerWindow with nodeIntegration as true at your main.js.

const mainWindow = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      nodeIntegration: true
    }
  })

And to read json file just this will be enough.

let quests = require('./quests-db.json');

One more thing. Json Object can't be iterable. For your case. you need to use like this.

for (const key in quests) {
  console.log(quests[key]);
}
...
$(body).append('<p>' + quests[key].title + '</p>);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM