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

13
  • 1
    The error means that the JSON is invalid. The way to deal with this is ensure the backend returns valid JSON.
    – VLAZ
    Commented Oct 9, 2019 at 13:46
  • How do I do that? I tried printing it in a file and see what the error is about. I have shared the error here. Does { seem wrong? Commented Oct 9, 2019 at 13:47
  • 2
    You have a structure like this: { "nodes": {}, {} }. Yes, this is invalid. You seem to want an array here. Commented Oct 9, 2019 at 13:49
  • 3
    Don't try to manage quoting and so on yourself. Build the data structure you want and export it using the json module that will take care of that. Commented Oct 9, 2019 at 13:51
  • 3
    I still don't understand why you would remove [ and ] as they are part of the integral structure of your json. Let the json module do the formatting for you, leave it alone. And don't dumps and then dump it again.
    – r.ook
    Commented Oct 9, 2019 at 13:56

1 Answer 1

1

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)

11
  • getting this error : Uncaught SyntaxError: Unexpected token N in JSON at position 54068 because of this {"source": NaN, "target": NaN}, How do I get rid of this Commented Oct 9, 2019 at 13:55
  • Don't output NaN as a value, as it's not valid in JSON.
    – VLAZ
    Commented Oct 9, 2019 at 13:57
  • @VLAZ: this is what json.dumps does (unless you provide allow_nan=False, in which case it breaks ;)
    – georg
    Commented Oct 9, 2019 at 13:59
  • @FatimaArshad: you have to remove NaN values before encoding them as JSON, see docs.python.org/3/library/math.html#math.isnan
    – georg
    Commented Oct 9, 2019 at 14:00
  • @georg that seems odd. I assume json is the library/functionality that generates JSON? If so, I wouldn't expect it to produce incorrect JSON.
    – VLAZ
    Commented Oct 9, 2019 at 14:03

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.