6

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}
Papouche Guinslyzinho
  • 4,877
  • 9
  • 49
  • 91
  • Possible duplicate of [Need to Pretty-Print JSON Data to a File using Python](https://stackoverflow.com/questions/9170288/need-to-pretty-print-json-data-to-a-file-using-python) – OneCricketeer Aug 28 '18 at 04:45
  • Does this seem like a suitable solution? [Json dumps escaping forward slashes](https://stackoverflow.com/questions/27129681/json-dumps-escaping-forward-slashes) – Matthew Aug 28 '18 at 04:45

3 Answers3

16

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)
iBug
  • 32,728
  • 7
  • 79
  • 117
  • Is there a simple test for `result`'s type? This way, one could write `if type(result) is : fp.write(result) ... else: json.dump(result,fp)` – blong May 01 '19 at 14:40
  • @blong `type(result) is str`, but better yet, keep track of your code and pay attention to *where* JSON is dumped. Only do it once, as stated in my answer. – iBug May 01 '19 at 14:59
1
data_json=df.to_json(orient='records')
parsed=json.loads(data_json)

with open('my_data.json', 'w') as f:
    json.dump(parsed, f, indent=4)
clemiblac
  • 11
  • 2
-1

The simplest way to solve the above problem is to play with json.dumps() and json.loads().

import json
result = json.dumps(result)

with open('result.json', 'w') as fp:
    json.loads(result, fp)
Rushabh Sudame
  • 374
  • 4
  • 20