如何在json中打印时添加双引号?目前我得到单引号

时间:2019-05-03 08:11:57

标签: python json python-3.x faker

代码

import json 
from faker import Faker
import random
from random import randint
fake = Faker('en_US')
for _ in range(1):
    sds =  {
      "id": "AB-asdfaf",
      "body": fake.sentence(),
      "time": fake.ean(),
      "hash": fake.ean(),
      "id1": fake.ean(),
      "user_id": "asdasdas",
      "id3": "test1"
    }

    print(sds)
我得到的

输出用单引号''表示。我需要获取json ijn双引号

输出:

 'body': 'Throughout third tough will PM time treat.'

我需要的输出:

"body": "Throughout third tough will PM time treat."

3 个答案:

答案 0 :(得分:3)

如果期望正确的JSON输出,则必须显式转换数据:

 print(json.dumps(sds))

这不仅涉及引号,FalseTrueNone在JSON中成为falsetruenull

答案 1 :(得分:0)

配额不是字符串的一部分,并且print()仅添加单个配额以表明您拥有字符串'123'或数字123

如果您使用模块json,那么您将获得格式正确的JSON,且配额是双重的

print( json.dumps(sds) )

完整代码

import json 
from faker import Faker
import random
from random import randint
fake = Faker('en_US')
for _ in range(1):
    sds =  {
      "id": "AB-asdfaf",
      "body": fake.sentence(),
      "time": fake.ean(),
      "hash": fake.ean(),
      "id1": fake.ean(),
      "user_id": "asdasdas",
      "id3": "test1"
    }

    print(json.dumps(sds))

结果:

{"id": "AB-asdfaf", "body": "Buy government couple.", "time": "6066358112738", "hash": "1204203048039", "id1": "0212772145043", "user_id": "asdasdas", "id3": "test1"}

答案 2 :(得分:-2)

您可以使用:

replace('\'', '\"'))