1

I am trying to read a json file generated through json.dump module in python and reading it in a javascript using JSON.parse. However, for some of the json dumps the javascript is throwing an exception for invalid literal. Does anyone know why this might happen or what should I do to prevent this?

Browsers: Chrome/Firefox; python ver: 2.7

EDIT1: based on the comment supplying some code

1) json dumped using

import json
json.dump(<python-dict>, open(<filename>,'w'), encoding='utf-8')``

2) Code read using

  • d3.json Output: a syntax error is thrown before the callback is called.
  • JSON.parse Outputs: invalid json

EDIT2: it may be relevant , the json dump is pretty large , around 24M uncompressed.

1
  • 1
    Could you post some relevant code please, easier to debug that way. :) Commented Jul 13, 2013 at 19:51

2 Answers 2

2

Just for the sake of completing the circle I found out the problem and the corresponding fix.

Firstly the problem:

The problem wasn't about not closing the file as some answers suggested or about the size being too big (as I thought initially). The problem was that my data before the json.dump part contained NAN's and by default json.dump (see json documentation) either allow nan's to be 'serialized' or throws an error (when 'allow_nan=False'). However, according to ECMA-262 NAN's are not allowed and hence the jquery json read was failing to read the dump.

The solution:

Use simplejson and use ignore_nan with it. The corrected code snippet should be

import simplejson
simplejson.dump(<python-dict>, open(<filename>,'w'), encoding='utf-8', ignore_nan=True)

Credits: sending NaN in json

Sign up to request clarification or add additional context in comments.

Comments

0

You're not closing the file, which will likely result in an incomplete file when you're trying to read that again.

How about

with open(filename, "w") as outfile:
    json.dump(myobject, outfile)

1 Comment

sorry about that.. its a typo... i did remember to give the object

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.