简体   繁体   English

SyntaxError:JSON.parse:JSON数据的第1行第1列出现意外字符吗?

[英]SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data?

Can anyone tell me why this code will work perfectly in an HTML page when accessing the data from my hard drive but when I add it to express and node I get a 谁能告诉我为什么从硬盘驱动器访问数据时,此代码为什么能在HTML页面中完美地工作,但是当我将其添加到express和node中时,会得到一个

SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data SyntaxError:JSON.parse:JSON数据的第1行第1列出现意外字符

with perfectly formatted code. 具有完美格式的代码。 I know I tested it with a formatter and I even manually created a json object. 我知道我使用格式化程序对其进行了测试,甚至手动创建了一个json对象。 Here is the code: 这是代码:

<html>
    <!doctype html>
    <html>
        <head>
            <meta charset="utf-8">
            <meta name="description" content="">
            <meta name="viewport" content="width=device-width, initial-scale=1">
            <title>Untitled</title>
        </head>
        <body>

    <div id="output"></div>

          <button id="getProperty">Get Property</button>

          <script>
            document.getElementById('getProperty').addEventListener('click', getProperty);


            function getProperty() {
                fetch('2016-regular.json')
                .then((res) => res.json())
                .then((data) => {
                    let output = '<h2>Property</h2>';
                    console.log(data);
                    data.propertystandings.propertystandingsentry.forEach(function(propertyEntry){
                        output += `
                            <ul>
                                <li>id: ${propertyEntry.property.ID}</li>
                                <li>city: ${propertyEntry.property.City}</li>
                                <li>prop name: ${propertyEntry.property.Name}</li>
                                <li>prop name: ${propertyEntry.rank}</li>
                            </ul>
                        `;
                    });
                document.getElementById('output').innerHTML = output;
                })
            }
          </script>

        </body>
    </html>
</html>
</html>
But then this code in express causes the error- same exact file that worked perfectly before ran thru express now causes this error: 
**"index.ejs"**

    <div id="output"></div>

          <button id="getProperty">Get Property</button>

    <script>

            document.getElementById('getProperty').addEventListener('click', getProperty);


            function getProperty() {
                /*fetch('sample.txt')
                .then(function(res) {
                    return res.text();
                })
                .then(function(data){
                    console.log(data);
                });*/
                fetch("2016-regular.json")
                .then((res) => res.json())
                .then((data) => {
                    console.log(data);//**won't even read the data without that error**
                });
            }
    </script>


**express code**
var express = require('express');
//var bodyParser = require('body-parser');
var cors = require('cors');
var path = require('path');

var app = express();

app.use(bodyParser());
app.use(cors());

app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

app.get('/', function (request, response) {
    response.render('index.ejs');
});

app.listen(8000, function() {
    console.log('running on 8000');
});

any ideas why this works fine in plain html when accessing a folder or if I manually create and save the file on my hard drive but once I put it in express or try to access the API the data came from (the final goal) I get the error SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data 任何想法,为什么在访问文件夹时这在纯HTML中都能正常工作,或者如果我手动在硬盘上创建并保存文件,但是一旦我将其放入Express或尝试访问API,数据就来自(最终目标)错误SyntaxError:JSON.parse:JSON数据第1行第1列的意外字符

I think the bottom line is that you need to make sure your JSON file is reachable/loadable, and then make sure it is valid. 我认为最重要的是,您需要确保JSON文件可访问/可加载,然后确保它是有效的。 Here is a minimal working example. 这是一个最小的工作示例。 You app.js should be simply: 您的app.js应该很简单:

var express = require('express');
var index = require('./routes/index');
var app = express();

app.set('views', 'views');
app.set('view engine', 'ejs');

app.use(express.static('public'));

app.use('/', index);

module.exports = app;

Your routes/index.js is simply: 您的route / index.js很简单:

var express = require('express');
var router = express.Router();

/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express' });
});

module.exports = router;

And your views/index.ejs should be: 您的views / index.ejs应该是:

<html>
<body>
  <div id="output">JSON contents will appear here.</div>  
  <button id="getProperty">Click to load JSON</button>

  <script>
      document.getElementById('getProperty').addEventListener('click', getProperty);  
      function getProperty() {
          fetch("./2016-regular.json")
          .then((res) => res.json())
          .then((data) => {
              document.getElementById('output').innerHTML = JSON.stringify(data);
          });
      }
  </script>
</body>
</html>     

Finally, make sure your JSON file is saved at ./public/2016-regular.json. 最后,确保将JSON文件保存在./public/2016-regular.json。 Here is mine: 这是我的:

{ "item1": "value1", "item2": "value2", "item3": "value3" } {“ item1”:“ value1”,“ item2”:“ value2”,“ item3”:“ value3”}

TEST 1 Make sure your JSON file is reachable my pointing your browser to http://localhost:3000/2016-regular.json (note you may have to change the port if you are running on a different port). 测试1将浏览器指向http:// localhost:3000 / 2016-regular.json,请确保您的JSON文件可访问(请注意,如果您在其他端口上运行,则可能必须更改端口)。

TEST 2 Navigate to http://localhost:3000/ and click on the button. 测试2导航到http:// localhost:3000 / ,然后单击按钮。 The file contents should appear in the results div. 文件内容应出现在结果div中。

Full working code is available here . 完整的工作代码 在这里 Just clone the repository, then 只需克隆存储库,然后

cd exp1
npm install
npm start

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 语法错误:JSON.parse:JSON 数据的第 1 行第 1 列出现意外字符 - SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data 语法错误json.parse json数据第1行第1列的意外字符 - syntaxerror json.parse unexpected character at line 1 column 1 of the json data SyntaxError:JSON.parse:JSON数据第3行第1列的意外字符 - SyntaxError: JSON.parse: unexpected character at line 3 column 1 of the JSON data SyntaxError:JSON.parse:JSON数据的第1行第2列出现意外字符 - SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON data SyntaxError: JSON.parse: JSON 第 1 行第 2 列的意外字符 - SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON JSON错误:SyntaxError:JSON.parse:JSON数据的第2行第1列出现意外字符 - JSON error : SyntaxError: JSON.parse: unexpected character at line 2 column 1 of the JSON data 无法显示数据。 SyntaxError:JSON.parse:JSON数据的第1行第1列出现意外字符 - Unable to show data. SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data 具有相同数据的Ajax错误(parsererror:SyntaxError:JSON.parse:JSON数据的第1行第1列出现意外字符) - Ajax error with the same data (parsererror: SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data) 我不断收到此错误SyntaxError:JSON.parse:JSON数据第1行第2列的意外字符 - I keep getting this error SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON data jQuery ajax语法错误json.parse json数据的第1行第1行出现意外字符 - Jquery ajax syntaxerror json.parse unexpected character at line 1 column 1 of the json data
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM