JSON字符串格式与python [英] Json string formatting with python

查看:60
本文介绍了JSON字符串格式与python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有任何方法可以格式化python中带有json的某个对象的结果字符串.例如,假设我有以下字典:

I'd like to know if there is any way to format the resulting strings of the enconding of some object with json in python. For example, suppose I have the following dictionary:

{'a': 12.73874, 'b': 1.74872, 'c': 8.27495}

,并且json编码的结果是:

and the result of the json encoding is:

{
    "c": 8.27495,
    "b": 1.74872,
    "a": 12.73874
}

而我想要的结果是:

{
    "a": 12.74,
    "c": 8.28,
    "b": 1.75
}

请注意元素的顺序和每个数字的小数位.有什么办法吗?

Notice the order of the elements and the decimal places of each number. Is there any way to do this?

提前谢谢!

推荐答案

您正在尝试将JSON用于不希望使用的内容,因此它不能很好地工作也就不足为奇了.您可以考虑使用 Python的 json 模块的源代码作为您自己的输出代码的起点,尽管从头开始可能很容易-编写这样的输出函数并不复杂.

You are trying to use JSON for something it's not intended for, so it's no surprise it does not work well. You could consider to use the source code of Python's json module as a starting point for your own output code, though it is probably easiest to start from scratch – it's not that complex a task to write such an output function.

这篇关于JSON字符串格式与python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆