如何解决javascript中JSON中意外的标记{语法错误
上面提到的是我的JSON的样子。它给出了错误,JSON中出现了意外的标记{。这个错误在名称:Enron worldwide之前抛出(在第二个开始之前)。我如何消除这个错误 这就是我生成JSON字符串的方式:如何解决javascript中JSON中意外的标记{语法错误,javascript,python,json,Javascript,Python,Json,上面提到的是我的JSON的样子。它给出了错误,JSON中出现了意外的标记{。这个错误在名称:Enron worldwide之前抛出(在第二个开始之前)。我如何消除这个错误 这就是我生成JSON字符串的方式: "{ \"nodes\": { \"name\": \"Enron Announcements\", \"counts\": { \"name\": \"Enron Announcements\", \"role\": \"em
"{ \"nodes\":
{ \"name\": \"Enron Announcements\", \"counts\": { \"name\": \"Enron Announcements\", \"role\": \"employee\", \"team_name\": \"Ufone\", \"oversees\": \"\", \"reports_to\": \"Zimin Lu,Lorna Brennan\", \"unique_threads\": \"366\" }, \"bridgeScore\": 0.0
},
{ \"name\": \"Enron worldwide\", \"counts\": { \"name\": \"Enron Announcements\", \"role\": \"employee\", \"team_name\": \"Ufone\", \"oversees\": \"\", \"reports_to\": \"Zimin Lu,Lorna Brennan\", \"unique_threads\": \"366\" }, \"bridgeScore\": 0.0
}, ...}
PS:json是通过python生成的,将在JS中呈现。您将对json进行两次编码。在代码中,删除
#return G
行后的所有内容,并将其替换为:
for i in graph.nodes():
if "nan" not in str(i):
nodes.append({'name': str(i), 'counts': user_data[str(i)], 'bridgeScore':bridgeScore[str(i)]})
links = [{'source': u[0], 'target': u[1]}
for u in graph.edges()]
for u in graph.edges():
print(u)
# with open('graph.json', 'w') as f:
# return G
graph_json = json.dumps({'nodes': nodes, 'links': links},indent=2,)
graph_json = str(graph_json).replace("\n","")
graph_json = str(graph_json).replace("[","")
graph_json = str(graph_json).replace("]","")
graph_json = str(graph_json).replace("\\","")
with open('temp.json','w') as fp:
json.dump(graph_json , fp)
如果需要从链接中删除nan
值,可以这样做:
graph_json = {'nodes': nodes, 'links': links}
with open('temp.json','w') as fp:
json.dump(graph_json , fp, indent=2)
(别忘了导入数学
)这个错误意味着JSON无效。处理这个问题的方法是确保后端返回有效的JSON。我该怎么做?我试着在一个文件中打印它,看看错误是什么。我在这里分享了这个错误。{似乎错了吗?你有这样的结构:{“节点”:{},{}
。是的,这是无效的。您似乎想要一个数组。不要自己尝试管理引用等。构建您想要的数据结构,并使用json
模块导出它,该模块将处理该问题。我仍然不明白您为什么要删除[
和]
因为它们是json整体结构的一部分。让json
模块为您进行格式化,别管它。不要转储
,然后再转储
它。获取此错误:Uncaught SyntaxError:json中的意外标记N位于54068位置,因为这个{“source”:NaN,“target”:NaN},我如何摆脱它?不要将NaN
作为一个值输出,因为它在JSON中无效。@VLAZ:JSON.dumps就是这样做的(除非您提供allow_NaN=False
,在这种情况下它会中断;)@Fatimarshad:在将NaN值编码为JSON之前,必须先删除它们,请参见@georg,这似乎有点奇怪。我假设JSON
是生成JSON的库/功能?如果是这样,我不希望它生成不正确的JSON。
links = [
{'source': u[0], 'target': u[1]}
for u in graph.edges()
if not math.isnan(u[0]) and not math.isnan(u[1])
]