itgeek
itgeek

Reputation: 589

replace quotes in json file using python

How to we convert singles quotes to double quotes in json file using python script.

file name: strings.json File content

[{'postId':'328e9497740b456154c636349','postTimestamp': '1521543600','pageType': '/home.php:topnews','viewTime': 1521545993647,'user_name': 'windows-super-user','gender': 3,'likes': '8','id': 'ffa1e07529ac917f6d573a','postImg': 1,'postDesc': [753],'origLink': 0,'duration': 0,'timestamp': 9936471521545,'back_time': 1521545993693},{'postId':'15545154c636349','postTimestamp': '547773600',        'pageType': '/home.php:topnews','viewTime': 45993647,'user_name': 'linux user','gender': 3,'likes': '8','id': '695e45a17f6d573a','postImg': 1,'postDesc': [953],'origLink': 0,'duration': 0,'timestamp': 545993647,'back_time': 85993693},{'postId':'9098897740b456154c636349','postTimestamp': '899943600',  'pageType': '/home.php:topnews','viewTime': 1521545993647,'user_name': 'unix_super_user','gender': 3,'likes': '8','id': '917f6d573a695e45affa1e07','postImg': 1,'postDesc': [253],'origLink': 0,'duration': 0,'timestamp': 193647,'back_time': 1521545993693}]

I have tried the below code, and it is not working;

with open('strings.json') as f:
    jstr = json.dump(f)
    print(jstr)

expected output:

[
    {
        "postId":"328e9497740b456154c636349",
        "postTimestamp": "1521543600",
        "pageType": "/home.php:topnews",
        "viewTime": 1521545993647,
        "user_name": "windows-super-user",
        "gender": 3,
        "likes": "8",
        "id": "ffa1e07529ac917f6d573a",
        "postImg": 1,
        "postDesc": [753],
        "origLink": 0,
        "duration": 0,
        "timestamp": 9936471521545,
        "back_time": 1521545993693
    },
    {
        "postId":"15545154c636349",
        "postTimestamp": "547773600",
        "pageType": "/home.php:topnews",
        "viewTime": 45993647,
        "user_name": "linux user",
        "gender": 3,
        "likes": "8",
        "id": "695e45a17f6d573a",
        "postImg": 1,
        "postDesc": [953],
        "origLink": 0,
        "duration": 0,
        "timestamp": 545993647,
        "back_time": 85993693
    }
]

Upvotes: 2

Views: 4074

Answers (1)

almiki
almiki

Reputation: 455

Single quotes are not valid for strings in JSON, so that file isn't valid JSON as far as any parser is concerned.

If you want to replace all single quotes with double quotes, just do something like:

# Read in the file contents as text
with open('strings.json') as f:
    invalid_json = f.read()

# Replace all ' with "
valid_json = invalid_json.replace("'", '"')

# Verify that the JSON is valid now and this doesn't raise an exception
json.loads(valid_json)

# Save the modified text back to the file
with open('strings.json.fixed', 'w') as f:
    f.write(valid_json)

Upvotes: 3

Related Questions