javascript - 如何解决 javascript 中 JSON 中的意外标记 { 语法错误

标签 javascript python json

"{  \"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/

相关文章:

javascript - 如何在一堆变换 P5.js 后获取原点的屏幕坐标

Javascript 获取元素 CSS 过渡阶段

javascript - angularJs - 如何获取过滤数组

python - 查找功能的参数

javascript - native react : How to stop child component rerendering on state change?

python - 带有中文标签的 networkx draw_graphviz

python - 解释器维护的整数缓存是怎么回事?

javascript - 为什么此密码验证码不适用于 jquery 表单向导?

javascript - 如何使用 Nunjucks 安全地将 JSON 渲染到内联 <script> 中?

javascript - Rally 2.1 SDK - 按迭代过滤用户故事