Python json dumps integer value

I use the below python code to manipulate a set of JSON files in a specified folder. I extract nt from the data and I want to create new key value pair. If I were to print nt on my screen I get values as shown below.

nt 223 
nt 286 
nt 315 

These looks like integers to me. However If I use Kibana visualization tool to process it says this (i.e NXT is an analysed string fields). I want these values to be recognized as integers? Does this have something to do with the way I am encoding my json file (ensure_ascii=True) or is JSON value always a string?

#Process 'new' events to extract more info from 'Messages'
rootDir = '/home/s_parts'
for dirName, subdirList, fileList in os.walk(rootDir):
     for fname in fileList:
        fname='s_parts/'+fname
        with open(fname, 'r+') as f:
            json_data = json.load(f)
            m = json_data['Msg']
            nt = int(re.findall(r"NXT:\s*([^,m)]*)",m)[0])
            json_data["NXT"] = nt
            f.seek(0)
            json.dump(json_data,f,ensure_ascii=True)

asked Apr 7, 2015 at 2:02

liv2hakliv2hak

14k48 gold badges145 silver badges255 bronze badges

1

It appears json.dump alone is most likely treating everything as strings. Using json.loads after it should convert it into a list or dict allowing you to use the json values as integers.

Example:

x = json.dumps({'1': 2, '3': 4}, ensure_ascii=True, sort_keys=True)
y = json.loads(x)
print(y)
print(y['3']+1)

Output:

{u'1': 2, u'3': 4}
5

You could convert the string value to int without using json.loads, however, converting it to a list or dict with json.loads is far easier to manage and retrieve values. If you are curious about the type your json.dump result is try doing:

x = json.dump(json_data,f,ensure_ascii=True)
print(type(x))

https://docs.python.org/3.3/library/json.html

answered Apr 7, 2015 at 2:49

l'L'll'L'l

43.2k9 gold badges90 silver badges139 bronze badges

6

The full-form of JSON is JavaScript Object Notation. It means that a script (executable) file which is made of text in a programming language, is used to store and transfer the data. Python supports JSON through a built-in package called json. To use this feature, we import the json package in Python script. The text in JSON is done through quoted-string which contains the value in key-value mapping within { }. It is similar to the dictionary in Python.

Note: For more information, refer to Read, Write and Parse JSON using Python
 

Json.dumps()

json.dumps() function converts a Python object into a json string.
 

Syntax: 
json.dumps(obj, *, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, default=None, sort_keys=False, **kw)
Parameters: 
obj: Serialize obj as a JSON formatted stream 
skipkeys: If skipkeys is True (default: False), then dict keys that are not of a basic type (str, int, float, bool, None) will be skipped instead of raising a TypeError. 
ensure_ascii: If ensure_ascii is True (the default), the output is guaranteed to have all incoming non-ASCII characters escaped. If ensure_ascii is False, these characters will be output as-is. 
check_circular: If check_circular is False (default: True), then the circular reference check for container types will be skipped and a circular reference will result in an OverflowError (or worse). 
allow_nan: If allow_nan is False (default: True), then it will be a ValueError to serialize out of range float values (nan, inf, -inf) in strict compliance of the JSON specification. If allow_nan is True, their JavaScript equivalents (NaN, Infinity, -Infinity) will be used. 
indent: If indent is a non-negative integer or string, then JSON array elements and object members will be pretty-printed with that indent level. An indent level of 0, negative, or “” will only insert newlines. None (the default) selects the most compact representation. Using a positive integer indent indents that many spaces per level. If indent is a string (such as “\t”), that string is used to indent each level. 
separators: If specified, separators should be an (item_separator, key_separator) tuple. The default is (‘, ‘, ‘: ‘) if indent is None and (‘, ‘, ‘: ‘) otherwise. To get the most compact JSON representation, you should specify (‘, ‘, ‘:’) to eliminate whitespace. 
default: If specified, default should be a function that gets called for objects that can’t otherwise be serialized. It should return a JSON encodable version of the object or raise a TypeError. If not specified, TypeError is raised. 
sort_keys: If sort_keys is True (default: False), then the output of dictionaries will be sorted by key. 
 

Example #1: Passing the Python dictionary to json.dumps() function will return a string. 
 

Python3

import json

Dictionary ={1:'Welcome', 2:'to',

            3:'Geeks', 4:'for',

            5:'Geeks'}

json_string = json.dumps(Dictionary)

print('Equivalent json string of input dictionary:',

      json_string)

print("        ")

print(type(json_string))

Output
 

Equivalent json string of dictionary: {“1”: “Welcome”, “2”: “to”, “3”: “Geeks”, “4”: “for”, “5”: “Geeks”} 
<class ‘str’>

Example #2: By setting the skipkeys to True(default: False) we automatically skip the keys that are not of basic type.
 

Python3

import json

Dictionary ={(1, 2, 3):'Welcome', 2:'to',

            3:'Geeks', 4:'for',

            5:'Geeks'}

json_string = json.dumps(Dictionary,

                         skipkeys = True)

print('Equivalent json string of dictionary:',

      json_string)

Output 
 

Equivalent json string of dictionary: {“2”: “to”, “3”: “Geeks”, “4”: “for”, “5”: “Geeks”} 
 

Example #3: 
 

Python3

import json

Dictionary ={(1, 2, 3):'Welcome', 2:'to',

            3:'Geeks', 4:'for',

            5:'Geeks', 6:float('nan')}

json_string = json.dumps(Dictionary,

                         skipkeys = True,

                         allow_nan = True)

print('Equivalent json string of dictionary:',

      json_string)

Output : 
 

Equivalent json string of dictionary: {“2”: “to”, “3”: “Geeks”, “4”: “for”, “5”: “Geeks”, “6”: NaN} 

Example #4: 
 

Python3

import json

Dictionary ={(1, 2, 3):'Welcome', 2:'to',

            3:'Geeks', 4:'for',

            5:'Geeks', 6:float('nan')}

json_string = json.dumps(Dictionary,

                         skipkeys = True,

                         allow_nan = True,

                         indent = 6)

print('Equivalent json string of dictionary:',

      json_string)

Output: 
 

Equivalent json string of dictionary: {
      "2": "to",
      "3": "Geeks",
      "4": "for",
      "5": "Geeks",
      "6": NaN
}

Example #5: 
 

Python3

import json

Dictionary ={(1, 2, 3):'Welcome', 2:'to',

            3:'Geeks', 4:'for',

            5:'Geeks', 6:float('nan')}

json_string = json.dumps(Dictionary,

                         skipkeys = True,

                         allow_nan = True,

                         indent = 6,

                         separators =(". ", " = "))

print('Equivalent json string of dictionary:',

      json_string)

Output: 
 

Equivalent json string of dictionary: {
      "2" = "to". 
      "3" = "Geeks". 
      "4" = "for". 
      "5" = "Geeks". 
      "6" = NaN
}

Example #6: 
 

Python3

import json

Dictionary ={'c':'Welcome', 'b':'to',

            'a':'Geeks'}

json_string = json.dumps(Dictionary,

                         indent = 6,

                         separators =(". ", " = "),

                         sort_keys = True)

print('Equivalent json string of dictionary:',

      json_string)

Output: 
 

Equivalent json string of dictionary: {
      "a" = "Geeks". 
      "b" = "to". 
      "c" = "Welcome"
}

Can JSON have int as value?

JSON does not have distinct types for integers and floating-point values. Therefore, the presence or absence of a decimal point is not enough to distinguish between integers and non-integers. For example, 1 and 1.0 are two ways to represent the same value in JSON.

What does JSON dump return?

dumps() takes in a json object and returns a string.

What does Python JSON dumps do?

The json. dumps() method allows us to convert a python object into an equivalent JSON object. Or in other words to send the data from python to json.

What's the difference between JSON dump and JSON dumps?

json. dump() method used to write Python serialized object as JSON formatted data into a file. json. dumps() method is used to encodes any Python object into JSON formatted String.