【发布时间】:2016-01-07 19:35:15
【问题描述】:
我已经实现了一个以 mongodb 格式存储数据的应用程序。我的收藏中有 10k 条记录,格式如下。
现在,我想改变json数据的格式,如下所述。
我想主要改变以下几点:
1) 时间戳属性:
{
"timestamp": {
"$numberLong": "1442888576971"
},
"checked": false,
"details": "abc def",
"text": "Other (I,SU,S)"
}
到
{
"timestamp": "1442888576971",
"checked": false,
"details": "abc def",
"text": "Other (I,SU,S)"
}
2)
"decision": {
"$numberLong": "1"
},
"condition": {
"$numberLong": "5"
}
到
"decision": "1",
"condition": "5"
输入json
{
"_id": {
"$oid": "5600baac79a89d0b0c9cfb6f"
},
"appData": {
"99390": {
"ABC": {
"trackeddata": [
{
"timestamp": {
"$numberLong": "1442888576971"
},
"checked": false,
"details": "abc def",
"text": "Other (I,SU,S)"
},
{
"timestamp": {
"$numberLong": "1442888578443"
},
"checked": false,
"details": "eft ghjy",
"text": "A (I,S)"
}
],
"selecteddata": [
{
"checked": false,
"details": "abc def",
"text": "A (I,S)"
}
],
"iconData": [
{
"timestamp": {
"$numberLong": "1442888573233"
},
"c1": "yellow",
"c2": "yellow",
"c3": "red"
},
{
"timestamp": {
"$numberLong": "1442888576972"
},
"c1": "yellow",
"c2": "yellow",
"c3": "yellow"
}
],
"decision": {
"$numberLong": "1"
},
"condition": {
"$numberLong": "5"
}
}
}
}
}
我写了下面的代码,但在这段代码中,我只能在本地进行更改。我无法通过引用更改主 json 对象中的数据,因此我不需要计算太多。
是否有任何有效的方法可以非常快速地更改整个文件中的上述两件事。
下面的代码不能完全正常工作。我离开它是因为我认为这不是真正有效的算法。
这是我的代码:
import json
with open("t2.json") as json_file:
json_data = json.load(json_file)
userset = set([])
userList = [];
userDict = {};
for i in json_data:
innerdata = i['appData']
for key, value in innerdata.items():
for key1,value1 in value.items():
innerdata2 = value1['trackeddata'];
if innerdata2:
for item in innerdata2:
print item;
if type(item) is dict:
for k1,v1 in item.items():
timedata = item['timestamp']
epochtime = "";
for k2,v2 in timedata.items():
epochtime = timedata['$numberLong']
print epochtime;
item['timestamp'] = epochtime;
print item['timestamp'];
print type(item['timestamp']);
if not userDict.has_key(key):
userDict[key] = [value];
else:
userDict[key].append(value)
userList.append(key);
#print userList;
my_set = set(userList)
with open('result.json', 'w') as fp:
json.dump(userDict, fp)
感谢您的宝贵时间。
【问题讨论】:
标签: python json mongodb python-2.7 python-3.x