【问题标题】:how to add double quotes while printing in json? Currently i am getting single quotes如何在 json 中打印时添加双引号?目前我得到单引号
【发布时间】:2019-09-21 18:14:37
【问题描述】:

代码

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."

【问题讨论】:

  • 这只是python的表示,你不用担心。你有什么问题?
  • 将其写入文件 - 您不必更改引号。
  • 将打印数百个随机数据并发布到其他地方。但它只会接受 " " 而不是 ' '
  • 没关系 - print() 使用单个配额在屏幕上显示它,但模块 json 将使用双配额写入它。
  • 在 jupyter 中尝试过相同的 ' ' 正在返回

标签: python json python-3.x faker


【解决方案1】:

如果您期望正确的 JSON 输出,您必须明确转换您的数据:

 print(json.dumps(sds))

不仅仅是引号,FalseTrueNone 在 JSON 中变成 falsetruenull

【讨论】:

    【解决方案2】:

    配额不是字符串的一部分,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"}
    

    【讨论】:

      【解决方案3】:

      你可以使用:

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

      【讨论】:

        猜你喜欢
        • 2022-01-13
        • 2015-11-17
        • 1970-01-01
        • 1970-01-01
        • 2022-01-04
        • 1970-01-01
        • 1970-01-01
        • 2011-05-08
        相关资源
        最近更新 更多