Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to remove a back slash from a JSON file

I want to create a json file like this:

{"946705035":4,"946706692":4 ...}

I am taking a column that only contains Unix Timestamp and group them.

result = data['Last_Modified_Date_unixtimestamp_no_time'].value_counts()

In [21]: result.head()
Out[21]: 
1508284800    131
1508716800    106
1508371200    101
1508457600     99
1508630400     96
Name: Last_Modified_Date_unixtimestamp_no_time, dtype: int64

transform to a dict

result = result.to_dict()
result
'''
{1507161600: 1,
 1507852800: 1,
 1508198400: 64,
 1508284800: 131,
 ...
 1535155200: 1,
 1535241600: 1}
'''

import json
result = json.dumps(result)

with open('result.json', 'w') as fp:
    json.dump(result, fp, indent=4)

result enter image description here this is the data structure that I expected

{"946705035":4,"946706692":4}
like image 454
Papouche Guinslyzinho Avatar asked Aug 28 '18 04:08

Papouche Guinslyzinho


People also ask

Why does my JSON have backslash?

Those backslashes are escape characters. They are escaping the special characters inside of the string associated with JSON response. You have to use JSON. parse to parse that JSON string into a JSON object.

How do I remove something from a JSON file?

To delete a JSON object from a list: Parse the JSON object into a Python list of dictionaries. Use the enumerate() function to iterate over the iterate over the list. Check if each dictionary is the one you want to remove and use the pop() method to remove the matching dict.


1 Answers

You're dumping the JSON twice, which causes quotes to be escaped on the second dump. (After the first json.dumps the result is only a string, so you're just dumping a string instead of a dict again)

import json
# result = json.dumps(result)

with open('result.json', 'w') as fp:
    json.dump(result, fp, indent=4)

Or remove the second dump:

import json
result = json.dumps(result)

with open('result.json', 'w') as fp:
    # json.dump(result, fp, indent=4)
    print(result, file=fp)
like image 173
iBug Avatar answered Nov 01 '22 12:11

iBug