json.loads() returns 一个字符串

json.loads() returns a string

为什么 json.loads() 返回一个字符串?这是我的代码:

import json

d = """{
    "reference": "123432",
    "business_date": "2019-06-18",
    "final_price": 40,
    "products": [
        {
            "quantity": 4,
            "original_price": 10,
            "final_price": 40,
        }
    ]
}"""

j = json.loads(json.dumps(d))
print(type(j))

输出:

<class 'str'>

它不应该返回一个 json 对象吗?这里需要做什么更改?

两点:

  1. 您的 products 键有错别字:"final_price": 40, 应该是 "final_price": 40(没有逗号)
  2. j 应该是 json.loads(d)

输出

dict

编辑

在 json 对象中不能有尾随逗号的原因在 post Can you use a trailing comma in a JSON object?

中解释

Unfortunately the JSON specification does not allow a trailing comma. There are a few browsers that will allow it, but generally you need to worry about all browsers.

ast.literal_eval: 安全地评估表达式节点或包含 Python 文字或容器显示的字符串。提供的字符串或节点只能包含以下 Python 文字结构:字符串、字节、数字、元组、列表、字典、集合、布尔值、None、字节和集合。 more details

import ast

d = """{
    "reference": "123432",
    "business_date": "2019-06-18",
    "final_price": 40,
    "products": [
        {
            "quantity": 4,
            "original_price": 10,
            "final_price": 40,
        }
    ]
}"""

data = ast.literal_eval(d)

print(data)
print(type(data))

O/P:

{'reference': '123432', 'business_date': '2019-06-18', 'final_price': 40, 'products': [{'quantity': 4, 'original_price': 10, 'final_price': 40}]}
<class 'dict'>

在您的代码中,d 应该是一个 JSON 字符串。如果是这样,您就不需要在加载之前转储它。

当我删除字符串引号时,这意味着 json.dumps 调用正在处理字典而不是字符串,一切似乎都很好:

import json

d = {
    "reference": "123432",
    "business_date": "2019-06-18",
    "final_price": 40,
    "products": [
        {
            "quantity": 4,
            "original_price": 10,
            "final_price": 40,
        }
    ]
}

j = json.loads(json.dumps(d))
print(type(j))

打印出来

<class 'dict'>

但是请注意,尝试将 json.loads 应用于现有字符串会产生错误,因为 JSON 不如 Python 宽容,并且不允许在列表和字典的结尾(参见 "final_price" 元素定义)。

1). d AND j 的类型将保持不变。

import json

d = """{
 "reference": "123432",
 "business_date": "2019-06-18",
 "final_price": 40,
 "products": [
    {
        "quantity": 4,
        "original_price": 10,
        "final_price": 40,
    }
    ]
}"""
print(type(d))

j = json.loads(json.dumps(d))
print(type(j))

2).现在两者都有字典类型:-

import json

d = {
 "reference": "123432",
 "business_date": "2019-06-18",
 "final_price": 40,
 "products": [
    {
        "quantity": 4,
        "original_price": 10,
        "final_price": 40,
    }
    ]
}
print(type(d))

j = json.loads(json.dumps(d))
print(type(j))

这就是我们使用 json 格式的原因。 希望对您有所帮助。