简体   繁体   中英

How to solve unexpected token { syntax error in JSON in javascript

"{  \"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    
    },  ...}

Above mentioned is what my JSON looks like. It is giving error that unexpected token { in Json. This error is thrown before name:Enron worldwide (before second one starts). How do I get rid of this error?

This is how I generated the JSON string:

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 is generated through python and is to be rendered in JS

You're encoding JSON twice. In your code, remove everything after the # return G line and replace it with:

graph_json = {'nodes': nodes, 'links': links}
with open('temp.json','w') as fp:
        json.dump(graph_json , fp, indent=2)

If you need to remove nan values from links , you can do it like this:

links = [
    {'source': u[0], 'target': u[1]}
    for u in graph.edges()
    if not math.isnan(u[0]) and not math.isnan(u[1])
]

(don't forget to import math )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM