goofd
goofd

Reputation: 2098

Python json dump not read by javascript JSON.parse

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

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

Upvotes: 1

Views: 2068

Answers (2)

goofd
goofd

Reputation: 2098

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

Upvotes: 2

Tim Pietzcker
Tim Pietzcker

Reputation: 336128

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)

Upvotes: 0

Related Questions