code base 5000
code base 5000

Reputation: 4102

Python, Need Long Value to be Integer

I'm trying to insert a unix timestamp using REST to a webservice. And when I convert the dictionary I get the value: 1392249600000L I need this value to be an integer.

So I tried int(1392249600000L) and I get 1392249600000L, still a long value.

The reason I need this is because the JSON webservice only accepts timestamsp with milliseconds in them, but when I pass the JSON value with the 'L' in it I get an invalid JSON Primative of value 1392249600000L error.

Can someone please help me resolve this? It seems like it should be so easy, but it's driving me crazy!

Upvotes: 1

Views: 1596

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1122342

You should not be using Python representations when you are sending JSON data. Use the json module to represent integers instead:

>>> import json
>>> json.dumps(1392249600000L)
'1392249600000'

In any case, the L is only part of the string representation to make debugging easier, making it clear you have a long, not int value. Don't use Python string representations for network communications, in any case.

For example, if you have a list of Python values, the str() representation of that list will also use repr() representations of the contents of the list, resulting in L postfixes for long integers. But json.dumps() handles such cases properly too, and handle other types correctly too (like Python None to JSON null, Python True to JSON true, etc.):

>>> json.dumps([1392249600000L, True, None])
'[1392249600000, true, null]'

Upvotes: 3

Related Questions