尝试使用python字典重新格式化JSON数据
I have been trying to format live JSON data coming from an API to be read in Django views. However, data coming is little complicated.
我一直在尝试格式化来自API的实时JSON数据,以便在Django视图中读取。但是,数据来得有点复杂。
I have incoming JSON data in format
我有格式的传入JSON数据
{ Time1:
{'A':'Value',
'B':'Value',
}
Time2:
{'A':'Value',
'B':'Value',
}
there are multiple time records....
}
I need to convert it into
我需要把它转换成
{
'Time': Time1
'A' : 'Value'
'B' : 'Value'
},
{
'Time': Time2
'A' : 'Value'
'B' : 'Value'
},
{
'Time': Time3
'A' : 'Value'
'B' : 'Value'
},
{
'Time': Time4
'A' : 'Value'
'B' : 'Value'
},...and so on
3 个解决方案
#1
0
You can use a list comprehension structure, (the code below has been tested using Python3.6):
您可以使用列表推导结构(下面的代码已经使用Python3.6进行了测试):
# Given your JSON has successfully been parsed into a dictionary
> input={'Time1': {'A':'Value1A', 'B':'Value1B'}, 'Time2': {'A','Value2A', 'B', 'Value2B'}}
# Iterate over the dictionary and build a new item out of each key/value couple
> transformed=[(v.update({'Time': k}) or v) for (k, v) in input.items()]
> print(transformed)
[
{
'A' : 'Value1A'
'B' : 'Value1B'
'Time': 'Time1'
},{
'A' : 'Value2A'
'B' : 'Value2B'
'Time': 'Time2'
}, …
]
What happens with (v.update({'Time': k}) or v)
?
Given v
is a dictionary, v.update(...)
will add a new entry to the instance (in other words, it mutates the instance). This method doesn't return the instance though but None
, fortunately wrapping the call between parenthesis gives the opportunity to build an expression that will ultimately return the v
instance. v
being a dict object (given it is not empty) it will be evaluated truthfully in a Boolean context, hence the (… or v)
construct.
(v.update({'Time':k})或v)会发生什么?鉴于v是一个字典,v.update(...)将向实例添加一个新条目(换句话说,它会改变实例)。虽然这个方法不返回实例但是None,幸运的是,在括号之间包装调用可以构建一个最终返回v实例的表达式。 v是一个dict对象(假设它不是空的)它将在布尔上下文中真实地计算,因此(...或v)构造。
更多相关文章
- 用 Python requests库 爬取网页数据
- 如何将两个列表中的数据写入csv中的列?
- 运用Python语言编写获取Linux基本系统信息(三):Python与数据库编
- 独立于数据库的MAX()函数在SQLAlchemy中
- 可变序列长度数据的分类
- Python基础数据类型-函数传参详解
- 如何在序列化后从查询中更新json数据?
- 腾讯应用宝采集数据分析
- 机器学习Python数据特征选定