如何使用python动态修改json中的datetime对象?
我正在尝试将JSON输出日期时间属性转换为以下内容: “路径”:“2021-03-30 19:35:51”改为类似的->“路径”:“FA\21\03\30\project” 我的做法:如何使用python动态修改json中的datetime对象?,python,mysql,json,Python,Mysql,Json,我正在尝试将JSON输出日期时间属性转换为以下内容: “路径”:“2021-03-30 19:35:51”改为类似的->“路径”:“FA\21\03\30\project” 我的做法: 查询MYSQL数据库以获取所需的属性 将结果另存为dict 将dict转换为JSON 自定义JSON日期时间(路径)对象 我尝试访问JSON对象进行转换,但始终遇到以下错误: AttributeError:“str”对象没有属性 输入: pid = 1 mycursor = db.cursor(dictiona
pid = 1
mycursor = db.cursor(dictionary=True)
mycursor.execute("SELECT o.id as id_room, l.id as id_layer, po.id as id_point, c_x_axis, c_y_axis, c_z_axis, p.id_project as pid, p.c_date_created as path FROM optimization.tbl_room o INNER JOIN platform.tbl_project p ON o.fk_project = p.id_project INNER JOIN optimization.tbl_layer l ON l.fk_room = o.id INNER JOIN optimization.tbl_point po ON po.id = l.fk_center_point WHERE id_project = " + str(pid))
results = mycursor.fetchall()
to_json = json.dumps(results, default=str)
print(to_json)
输出结果:
[{'id_room': 1, 'id_layer': 1, 'id_point': 1, 'c_x_axis': -3.38823, 'c_y_axis': 2.41626, 'c_z_axis': 0.0, 'pid': 1, 'path': datetime.datetime(2021, 3, 30, 19, 35, 51)}, {'id_room': 2, 'id_layer': 2, 'id_point': 1, 'c_x_axis': -3.38823, 'c_y_axis': 2.41626, 'c_z_axis': 0.0, 'pid': 1, 'path': datetime.datetime(2021, 3, 30, 19, 35, 51)}, {'id_room': 3, 'id_layer': 3, 'id_point': 1, 'c_x_axis': -3.38823, 'c_y_axis': 2.41626, 'c_z_axis': 0.0, 'pid': 1, 'path': datetime.datetime(2021, 3, 30, 19, 35, 51)}, {'id_room': 4, 'id_layer': 4, 'id_point': 1, 'c_x_axis': -3.38823, 'c_y_axis': 2.41626, 'c_z_axis': 0.0, 'pid': 1, 'path': datetime.datetime(2021, 3, 30, 19, 35, 51)}, {'id_room': 5, 'id_layer': 5, 'id_point': 1, 'c_x_axis': -3.38823, 'c_y_axis': 2.41626, 'c_z_axis': 0.0, 'pid': 1, 'path': datetime.datetime(2021, 3, 30, 19, 35, 51)}, {'id_room': 6, 'id_layer': 6, 'id_point': 1, 'c_x_axis': -3.38823, 'c_y_axis': 2.41626, 'c_z_axis': 0.0, 'pid': 1, 'path': datetime.datetime(2021, 3, 30, 19, 35, 51)}, {'id_room': 7, 'id_layer': 7, 'id_point': 1, 'c_x_axis': -3.38823, 'c_y_axis': 2.41626, 'c_z_axis': 0.0, 'pid': 1, 'path': datetime.datetime(2021, 3, 30, 19, 35, 51)}, {'id_room': 8, 'id_layer': 8, 'id_point': 1, 'c_x_axis': -3.38823, 'c_y_axis': 2.41626, 'c_z_axis': 0.0, 'pid': 1, 'path': datetime.datetime(2021, 3, 30, 19, 35, 51)}, {'id_room': 9, 'id_layer': 9, 'id_point': 1, 'c_x_axis': -3.38823, 'c_y_axis': 2.41626, 'c_z_axis': 0.0, 'pid': 1, 'path': datetime.datetime(2021, 3, 30, 19, 35, 51)}, {'id_room': 10, 'id_layer': 10, 'id_point': 1, 'c_x_axis': -3.38823, 'c_y_axis': 2.41626, 'c_z_axis': 0.0, 'pid': 1, 'path': datetime.datetime(2021, 3, 30, 19, 35, 51)}, {'id_room': 11, 'id_layer': 11, 'id_point': 1, 'c_x_axis': -3.38823, 'c_y_axis': 2.41626, 'c_z_axis': 0.0, 'pid': 1, 'path': datetime.datetime(2021, 3, 30, 19, 35, 51)}, {'id_room': 12, 'id_layer': 12, 'id_point': 1, 'c_x_axis': -3.38823, 'c_y_axis': 2.41626, 'c_z_axis': 0.0, 'pid': 1, 'path': datetime.datetime(2021, 3, 30, 19, 35, 51)}, {'id_room': 13, 'id_layer': 13, 'id_point': 1, 'c_x_axis': -3.38823, 'c_y_axis': 2.41626, 'c_z_axis': 0.0, 'pid': 1, 'path': datetime.datetime(2021, 3, 30, 19, 35, 51)}, {'id_room': 14, 'id_layer': 14, 'id_point': 1, 'c_x_axis': -3.38823, 'c_y_axis': 2.41626, 'c_z_axis': 0.0, 'pid': 1, 'path': datetime.datetime(2021, 3, 30, 19, 35, 51)}]
输出到_json:
{"id_room": 1, "id_layer": 1, "id_point": 1, "c_x_axis": -3.38823, "c_y_axis": 2.41626, "c_z_axis": 0.0, "pid": 1, "path": "2021-03-30 19:35:51"}
非常感谢您提供有关如何进行的任何帮助。只需修改sql查询并使用DATE_格式即可获得所需的输出:
"SELECT o.id as id_room, l.id as id_layer, po.id as id_point, c_x_axis, c_y_axis, c_z_axis, p.id_project as pid,
DATE_FORMAT(p.c_date_created,'FA\\%Y\\%m\\%d\\project') as path
FROM optimization.tbl_room o INNER JOIN platform.tbl_project p ON o.fk_project = p.id_project INNER JOIN optimization.tbl_layer l ON l.fk_room = o.id INNER JOIN optimization.tbl_point po ON po.id = l.fk_center_point
WHERE id_project = " + str(pid))
此外,您应该在execute命令中使用%s来标识变量。
因此,您的代码如下所示,具体取决于您使用哪个库访问MySQL:
pid = 1
sql_query = """
SELECT o.id as id_room, l.id as id_layer, po.id as id_point, c_x_axis, c_y_axis, c_z_axis, p.id_project as pid,
DATE_FORMAT(p.c_date_created,'FA\\%Y\\%m\\%d\\project') as path
FROM optimization.tbl_room o INNER JOIN platform.tbl_project p ON o.fk_project = p.id_project INNER JOIN optimization.tbl_layer l ON l.fk_room = o.id INNER JOIN optimization.tbl_point po ON po.id = l.fk_center_point
WHERE id_project = %s
"""
mycursor = db.cursor(dictionary=True) # you should use "_" to separate words eg:"my_cursor"
variables:tuple = (pid,)
# be aware of the ","
# if you had n variables you would write
# variables:tuple = (variable_1, variable_2,..., variable_n)
mycursor.execute(sql_query, variables)
results = mycursor.fetchall()
to_json = json.dumps(results, default=str) # avoid using function alike wording and prefer: "result_to_json"
print(to_json)
参考文献:
通常情况下,您可能不希望twick json结果,因为当它失败时,它会向您提供信息/引发错误。我通常处理特定情况的方法(当我知道将遵循一种信息模式时)是提供json.dump类来处理特定python类到字符串的转换):
使用:
from uuid import UUID # which could have been datetime
import json
class UUIDEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, UUID):
# if the obj is uuid, we simply return the value of uuid
return obj.hex
return json.JSONEncoder.default(self, obj)
json_dump = json.dumps(list_of_dicts, cls=UUIDEncoder)
Last, and depending of the flexibility you have and since you are flagged as a "New Contributor", you may want to use PostGresSQL, rather than MySQL.
It gives you much more functions that you may want to use at a later stage (only a Nota Bene).
I hope this kicks you off.
Best
如果要将json字符串转换为python对象,则需要执行
json.load(…)
。谢谢!实际上,我想修改JSON中的路径值,而不是将JSON转换为对象to_json=json.load(results)
。然后将路径值修改为_json['path']='new_path'
,最后,json.dumps(result)
尝试加载,但它告诉我无法加载列表,因此我再次遇到与以前相同的问题,无法访问path属性。您可以更改sql查询以获得所需的输出:SELECT DATE\u格式(“2021-03-30”、“FA\\%Y\\%m\\%d\\project”)或使用您的查询变量:DATE_FORMAT(p.c_DATE_created,'FA\\\%Y\\\%m\\\%d\\project')作为路径非常感谢!这解决了我的问题,使用DATE_CREATE我能够正确创建路径。很好,我已经使用变量编辑了答案,希望这有帮助,您可能会发现编写代码更容易(例如,不需要强制转换类(如果它们在预期类中)
from uuid import UUID # which could have been datetime
import json
class UUIDEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, UUID):
# if the obj is uuid, we simply return the value of uuid
return obj.hex
return json.JSONEncoder.default(self, obj)
json_dump = json.dumps(list_of_dicts, cls=UUIDEncoder)
Last, and depending of the flexibility you have and since you are flagged as a "New Contributor", you may want to use PostGresSQL, rather than MySQL.
It gives you much more functions that you may want to use at a later stage (only a Nota Bene).
I hope this kicks you off.
Best