简体   繁体   English

合并两个有效的json对象时出现意外的令牌错误

[英]Unexpected token error when combining two valid json object

I am doing a web application which needs to load a JSON file from the server, when I try to parse that file I encountered the Unexpected Token error. 我正在做一个Web应用程序,当我尝试解析该文件时,我需要从服务器加载JSON文件,我遇到了Unexpected Token错误。 I then find out the problem happens when two items appear in one file 然后我发现当一个文件中出现两项时会发生问题

Here is the two JSON items: 这是两个JSON项目:

{
    "黄南":{"id":10973,"name":"黄南","prov":"青海","latt":35.519549,"logi":102.015248}, 
    "海北":{"id":10970,"name":"海北","prov":"青海","latt":36.954413,"logi":100.900998}
}

I have tried JSON.parse in chrome console, json.loads in python and JSONlint.com , they all raise errors. 我曾尝试JSON.parse铬控制台, json.loads Python和JSONlint.com ,他们都引发错误。

The interesting part is that when I tried to load them individually, there was no error, but as long as they are loaded together, the error is thrown out 有趣的部分是,当我尝试分别加载它们时,没有错误,但是只要将它们一起加载,就会抛出错误

So can anyone tell me what is happening and how to avoid this? 那么谁能告诉我发生了什么以及如何避免这种情况? Thank you guys and sorry if there is any gramma issues in my description. 谢谢大家,如果我的描述中有任何语法问题,我们深表歉意。

It's a guess without more info, but I'm guessing python 2.x without setting the encoding, because other than that there is no other reason. 这是没有更多信息的猜测,但是我猜测python 2.x没有设置编码,因为除此之外,没有其他原因。

Tried the most basic operations available in 3.4 and 2.7. 尝试了3.4和2.7中可用的最基本的操作。 It works without issue in 3.4. 它在3.4中没有问题。 In 2.7, you need to use utf-8 or you'd get an error. 在2.7版中,您需要使用utf-8,否则会出现错误。

this will work with python 3.x but fail in 2.x 这将适用于python 3.x,但在2.x中失败

#!/usr/bin/env python3.4
import json
j = """{
    "黄南":{"id":10973,"name":"黄南","prov":"青海","latt":35.519549,"logi":102.015248},
    "海北":{"id":10970,"name":"海北","prov":"青海","latt":36.954413,"logi":100.900998}
}"""

o = json.loads(j)
print(json.dumps(o,indent=1))

This will work in 2.7, probably 2.6 too 这将在2.7或2.6中运行

#!/usr/bin/env python2.7
# -*- coding: utf-8 -*-
import json
j = """{
    "黄南":{"id":10973,"name":"黄南","prov":"青海","latt":35.519549,"logi":102.015248},
    "海北":{"id":10970,"name":"海北","prov":"青海","latt":36.954413,"logi":100.900998}
}"""

o = json.loads(j)
print(json.dumps(o,indent=1))

意外标记 '&lt;', "<div id="text_translate"><p> 我是 Reactjs 的初学者和 StackOverflow 的新手。 实际上,我正在尝试将数据从后端传递到前端。 但不是从后端 url 获取 JSON 数据,而是从前端的 index.html 获取数据。 我的后端是nodejs。 基本上,我想从后端获取 JSON 数据并将数据发布到前端的控制台中。 但我得到这个SyntaxError: Unexpected token '&lt;', "&lt;.DOCTYPE "... is not valid JSON谁能帮我解决这个问题。 <a href="/questions/tagged/reactjs" class="post-tag" title="显示标记为“reactjs”的问题" aria-label="show questions tagged 'reactjs'" rel="nofollow noreferrer" aria-labelledby="reactjs-container">reactjs</a> <a href="/questions/tagged/nodejs" class="post-tag" title="显示标记为“nodejs”的问题" aria-label="show questions tagged 'nodejs'" rel="nofollow noreferrer" aria-labelledby="nodejs-container">nodejs</a></p><p> <strong>前端代码</strong></p><pre>App.js import React from 'react'; import {useState, useEffect} from 'react'; import {getOrder} from './ApiCalls.js' function App() { const[values, setValues]=useState({ amount:0, orderId:'' }) const{amount, orderId}=values useEffect(() =&gt; { createorder() }, []) const createorder=()=&gt;{ getOrder().then(response=&gt;console.log(response)) } const showRazorPay=()=&gt;{ const form=document.createElement('form') form.setAttribute('action',`${process.env.REACT_APP_BACKEND}/payment/callback`); form.setAttribute('method',"POST"); const script=document.createElement("script"); script.src= "https://checkout.razorpay.com/v1/checkout.js"; script.setAttribute("data-key",process.env.REACT_APP_DATA_KEY); script.setAttribute("data-amount", amount); script.setAttribute("data-prefill.contact","9561315545"); script.setAttribute("data-order_id", orderId); script.setAttribute("data-prefill.name", "Priyanka Chaudhari"); script.setAttribute("data-image", `${process.env.REACT_APP_BACKEND}/logo`) script.setAttribute("data-buttontext","Donate Now;"). document.body;appendChild(form). form;appendChild(script). const input= document;createElement("input"). input;type="hidden". input;custom="Hidden Element"; } return ( &lt;div&gt; &lt;/div&gt; ); } export default App;</pre><pre> ApiCalls.js export const getOrder=()=&gt;{ return fetch(`${process.env.REACT_APP_BACKEND}/createorder`,{ method: "GET", headers: { 'Content-Type':'application/json' } }).then(response=&gt;response.json()).catch((err)=&gt;console.log(err)) }</pre><p> <strong>后端代码</strong></p><pre>App.js const express=require('express') const bodyParser=require('body-parser') const cors=require('cors') const app=express() const PaymentRoute=require('./PaymentRoute') app.use(bodyParser.json()) app.use(cors()) app.use('/api',PaymentRoute); app.listen(5000,()=&gt;{ console.log(`App is running at 5000 port`) })</pre><pre> PaymentRoute.js const express=require('express') const router=express.Router() const{CreateOrder,paymentCallback,getLogo}=require('./PaymentController') router.get('/createorder',CreateOrder); router.post('/payment/callback',paymentCallback) router.get('/logo',getLogo) module.exports=router;</pre><pre> PaymentController.js require('dotenv').config() const Razorpay=require('razorpay') const uniqueId=require('uniqid') const path=require('path') var instance = new Razorpay({ key_id: process.env.KEY_ID, key_secret: process.env.SECRET_KEY }) // instance.payments.fetch(paymentId) exports.CreateOrder=(req,res)=&gt;{ var options = { amount: 50000, // amount in the smallest currency unit currency: "INR", receipt: uniqueId() }; instance.orders.create(options, function(err, order) { if(err){ return res.status(500).json({ error:err }) } res.json(order) }); } exports.paymentCallback=(req,res)=&gt;{ } exports.getLogo=(req,res)=&gt;{ res.sendFile(path.join(__dirname,'donate-image.png')) }</pre></div> - Unexpected token '<', "<!DOCTYPE "... is not valid JSON

暂无
暂无

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

相关问题 未捕获的语法错误意外的令牌:,但是服务器从服务器接收到有效的json对象 - Uncaught Syntax Error Unexpected token : , but the server received a valid json object from the server 意外标记 '&lt;', "<div id="text_translate"><p> 我是 Reactjs 的初学者和 StackOverflow 的新手。 实际上,我正在尝试将数据从后端传递到前端。 但不是从后端 url 获取 JSON 数据,而是从前端的 index.html 获取数据。 我的后端是nodejs。 基本上,我想从后端获取 JSON 数据并将数据发布到前端的控制台中。 但我得到这个SyntaxError: Unexpected token '&lt;', "&lt;.DOCTYPE "... is not valid JSON谁能帮我解决这个问题。 <a href="/questions/tagged/reactjs" class="post-tag" title="显示标记为“reactjs”的问题" aria-label="show questions tagged 'reactjs'" rel="nofollow noreferrer" aria-labelledby="reactjs-container">reactjs</a> <a href="/questions/tagged/nodejs" class="post-tag" title="显示标记为“nodejs”的问题" aria-label="show questions tagged 'nodejs'" rel="nofollow noreferrer" aria-labelledby="nodejs-container">nodejs</a></p><p> <strong>前端代码</strong></p><pre>App.js import React from 'react'; import {useState, useEffect} from 'react'; import {getOrder} from './ApiCalls.js' function App() { const[values, setValues]=useState({ amount:0, orderId:'' }) const{amount, orderId}=values useEffect(() =&gt; { createorder() }, []) const createorder=()=&gt;{ getOrder().then(response=&gt;console.log(response)) } const showRazorPay=()=&gt;{ const form=document.createElement('form') form.setAttribute('action',`${process.env.REACT_APP_BACKEND}/payment/callback`); form.setAttribute('method',"POST"); const script=document.createElement("script"); script.src= "https://checkout.razorpay.com/v1/checkout.js"; script.setAttribute("data-key",process.env.REACT_APP_DATA_KEY); script.setAttribute("data-amount", amount); script.setAttribute("data-prefill.contact","9561315545"); script.setAttribute("data-order_id", orderId); script.setAttribute("data-prefill.name", "Priyanka Chaudhari"); script.setAttribute("data-image", `${process.env.REACT_APP_BACKEND}/logo`) script.setAttribute("data-buttontext","Donate Now;"). document.body;appendChild(form). form;appendChild(script). const input= document;createElement("input"). input;type="hidden". input;custom="Hidden Element"; } return ( &lt;div&gt; &lt;/div&gt; ); } export default App;</pre><pre> ApiCalls.js export const getOrder=()=&gt;{ return fetch(`${process.env.REACT_APP_BACKEND}/createorder`,{ method: "GET", headers: { 'Content-Type':'application/json' } }).then(response=&gt;response.json()).catch((err)=&gt;console.log(err)) }</pre><p> <strong>后端代码</strong></p><pre>App.js const express=require('express') const bodyParser=require('body-parser') const cors=require('cors') const app=express() const PaymentRoute=require('./PaymentRoute') app.use(bodyParser.json()) app.use(cors()) app.use('/api',PaymentRoute); app.listen(5000,()=&gt;{ console.log(`App is running at 5000 port`) })</pre><pre> PaymentRoute.js const express=require('express') const router=express.Router() const{CreateOrder,paymentCallback,getLogo}=require('./PaymentController') router.get('/createorder',CreateOrder); router.post('/payment/callback',paymentCallback) router.get('/logo',getLogo) module.exports=router;</pre><pre> PaymentController.js require('dotenv').config() const Razorpay=require('razorpay') const uniqueId=require('uniqid') const path=require('path') var instance = new Razorpay({ key_id: process.env.KEY_ID, key_secret: process.env.SECRET_KEY }) // instance.payments.fetch(paymentId) exports.CreateOrder=(req,res)=&gt;{ var options = { amount: 50000, // amount in the smallest currency unit currency: "INR", receipt: uniqueId() }; instance.orders.create(options, function(err, order) { if(err){ return res.status(500).json({ error:err }) } res.json(order) }); } exports.paymentCallback=(req,res)=&gt;{ } exports.getLogo=(req,res)=&gt;{ res.sendFile(path.join(__dirname,'donate-image.png')) }</pre></div> - Unexpected token '<', "<!DOCTYPE "... is not valid JSON 解析有效的JSON时出现&#39;Uncaught SyntaxError:Unexpected token:&#39; - 'Uncaught SyntaxError: Unexpected token :' when parsing valid JSON 从asyncStorage获取时的JSON.parse(object)引发错误:位置1的JSON中的意外令牌o - JSON.parse(object) when getting from asyncStorage throws error: Unexpected token o in JSON at position 1 当您在json中有两行时,如何解决意外的令牌错误? - How to resolve unexpected token error when you have two lines in json? 尝试在简单对象上执行JSON.parse时出现“意外令牌”错误 - I am getting an “Unexpected token” error when trying to do JSON.parse on a simple object 未捕获的SyntaxError:意外的令牌:对于有效的JSON - Uncaught SyntaxError: Unexpected token : for a valid JSON 使用Javascript将字符串转换为对象(错误:JSON中位置1处的意外令牌t) - Converting string to object with Javascript (Error: Unexpected token t in JSON at position 1) 使用JSON.parse将字符串(变量)转换为对象,错误意外令牌 - Convert a string (variable ) to object with JSON.parse , error unexpected token SyntaxError意外令牌{在JavaScript中使用json对象时 - SyntaxError unexpected token { when using json object in JavaScript
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM