"{ \"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
}, ...}
上面提到的是我的 JSON 的样子。 Json 中的意外标记 { 给出了错误。此错误在 name:Enron worldwide 之前抛出(在第二个开始之前)。我如何摆脱这个错误?
这是我生成 JSON 字符串的方式:
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)
PS:json是通过python生成的,是用JS渲染的
最佳答案
您对 JSON 进行了两次编码。在您的代码中,删除 # return G
行之后的所有内容并将其替换为:
graph_json = {'nodes': nodes, 'links': links}
with open('temp.json','w') as fp:
json.dump(graph_json , fp, indent=2)
如果您需要从 links
中删除 nan
值,您可以这样做:
links = [
{'source': u[0], 'target': u[1]}
for u in graph.edges()
if not math.isnan(u[0]) and not math.isnan(u[1])
]
(不要忘记导入数学
)
关于javascript - 如何解决 javascript 中 JSON 中的意外标记 { 语法错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58305626/