настраиваемый формат OrderedDict и перевод в словарь - PullRequest
0 голосов
/ 02 ноября 2018

У меня проблема с настройкой формата OrderedDict и преобразованием их в формат json или словарь (но я могу сбросить имена ключей и структуру). У меня есть данные ниже:

result= OrderedDict([('index', 'cfs_fsd_00001'),
                     ('host', 'GIISSP707'),
                     ('source', 'D:\\usrLLSS_SS'),
                     ('_time', '2018-11-02 14:43:30.000 EDT'),
                     ('count', '153')])

... Однако я хочу изменить формат следующим образом:

{
 "servarname": {
    "index": "cfs_fsd_00001",
    "host": "GIISSP707"
 },
 "times": '2018-11-02 14:43:30.000 EDT',
 "metricTags": {
    "source": 'D:\\ddevel.log'"
 },
 "metricName": "serverice count",
 "metricValue": 153,
 "metricType": "count"
}

Я буду очень признателен за вашу помощь. В основном результат, который я получил, довольно плоский. Но я хочу настроить структуру. Исходная структура

OrderedDict ([('index', 'cfs_fsd_00001'), ('host', 'GIISSP707') .....]).

Вывод, который я хочу получить: {"servarname" {"index": "cfs_fsd_00001", "host": "GIISSP707"}, ......

Ответы [ 2 ]

0 голосов
/ 06 ноября 2018

Не уверен, насколько вам нужен гибкий метод. Я предполагаю, что у вас есть несколько общих ключей в вашем OrderedDict, и вы хотите найти метрику там, а затем переформатировать их в новый диктат. Вот короткая функция, которая реализована в Python 3, и я надеюсь, что она может помочь.

from collections import OrderedDict
import json

def reformat_ordered_dict(dict_result):
    """Reconstruct the OrderedDict result into specific format

    This method assumes that your input OrderedDict has the following common keys: 'index',
    'host', 'source', '_time', and a potential metric whcih is subject to change (of course
    you can support more metrics with minor tweak of the code). The function also re-map the
    keys (for example, mapping '_time' to 'times', pack 'index' and 'source' into 'servarname'
    ).
    :param dict_result: the OrderedDict
    :return: the reformated OrderedDict
    """
    common_keys = ('index', 'host', 'source', '_time')
    assert all(common_key in dict_result for common_key in common_keys), (
        'You have to provide all the commen keys!')

    # write common keys
    reformated = OrderedDict()
    reformated["servarname"] = OrderedDict([
        ("index", dict_result['index']),
        ("host", dict_result['host'])
    ])
    reformated["times"] = dict_result['_time']
    reformated["metricTags"] = {"source": dict_result['source']}

    # write metric
    metric = None
    for key in dict_result.keys():
        if key not in common_keys:
            metric = key
            break

    assert metric is not None, 'Cannot find metric in the OrderedDict!'

    # don't know where you get this value. But you can customize it if needed
    # for exampe if the metric name is needed here
    reformated['metricName'] = "serverice count"
    reformated['metricValue'] = dict_result[metric]
    reformated['metricType'] = metric

    return reformated

if __name__ == '__main__':
    result= OrderedDict([('index', 'cfs_fsd_00001'),
                     ('host', 'GIISSP707'),
                     ('source', 'D:\\usrLLSS_SS'),
                     ('_time', '2018-11-02 14:43:30.000 EDT'),
                     ('count', '153')])
    reformated = reformat_ordered_dict(result)
    print(json.dumps(reformated))
0 голосов
/ 02 ноября 2018

Вы можете просто ссылаться на диктовку result с соответствующими ключами, которые вы хотите, чтобы ваша целевая структура данных имела:

{
    "servarname": {
        "index": result['index'],
        "host": result['host']
    },
    "times": result['_time'],
    "metricTags": {
        "source": result['source']
    },
    "metricName": "serverice count",
    "metricValue": result['count'],
    "metricType": "count"
}
...