【问题标题】:Change json object data by reference in Python在 Python 中通过引用更改 json 对象数据
【发布时间】: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


    【解决方案1】:

    您需要遍历ABC 数组中的每个键,然后设置timestamp 的值(如果该键在['trackedata', 'iconData']['condition', 'decision'] 中)

    >>> import json
    >>> with open('input.json') as inf, \
    ...      open('output.json', 'w') as outf:
    ...     init_data = json.load(inf)
    ...     appData = init_data['appData']
    ...     for key in appData:
    ...         abc = appData[key]['ABC']
    ...         for subkeys in abc:
    ...             if subkeys in ['condition', 'decision']:
    ...                 abc[subkeys] = abc[subkeys]['$numberLong']
    ...             if subkeys in ['trackeddata', 'iconData']:
    ...                 for element in abc[subkeys]:
    ...                     element['timestamp'] = element['timestamp']['$numberLong']
    ...     json.dump(init_data, outf)
    ... 
    

    您的 output.json 如下所示:

    >>> from pprint import pprint
    >>> pprint(init_data)
    {'_id': {'$oid': '5600baac79a89d0b0c9cfb6f'},
     'appData': {'99390': {'ABC': {'condition': '5',
                                   'decision': '1',
                                   'iconData': [{'c1': 'yellow',
                                                 'c2': 'yellow',
                                                 'c3': 'red',
                                                 'timestamp': '1442888573233'},
                                                {'c1': 'yellow',
                                                 'c2': 'yellow',
                                                 'c3': 'yellow',
                                                 'timestamp': '1442888576972'}],
                                   'selecteddata': [{'checked': False,
                                                     'details': 'abc def',
                                                     'text': 'A (I,S)'}],
                                   'trackeddata': [{'checked': False,
                                                    'details': 'abc def',
                                                    'text': 'Other (I,SU,S)',
                                                    'timestamp': '1442888576971'},
                                                   {'checked': False,
                                                    'details': 'eft ghjy',
                                                    'text': 'A (I,S)',
                                                    'timestamp': '1442888578443'}]}}}}
    >>> 
    

    【讨论】:

    猜你喜欢
    • 2019-01-11
    • 1970-01-01
    • 2020-08-11
    • 2013-03-11
    • 2022-12-23
    • 2018-12-14
    • 2021-12-25
    • 2023-03-14
    • 1970-01-01
    相关资源
    最近更新 更多