代码之家  ›  专栏  ›  技术社区  ›  Prasanna Nandakumar

更改JSON键以返回API

  •  0
  • Prasanna Nandakumar  · 技术社区  · 6 年前

    我从DynamoDB读取一个表,并将其作为JSON对象发送到API。我想更改JSON密钥名 (reg,dreg,stat,num) (a,b,c,d)

    import boto3
    import json
    import re
    
    def lambda_handler(event, context):
        dynamodb = boto3.resource('dynamodb', region_name='xx-xxxxxxx-1')
        table = dynamodb.Table('_master')
    
        response = table.scan()
        data =[sanitize(item) for item in response['Items']]
    
        while 'LastEvaluatedKey' in response:
            response = table.scan(ExclusiveStartKey=response['LastEvaluatedKey'])
            data.extend(sanitize(item) for item in response['Items'])
    
    
        return {
            'statusCode': 200,
            'headers': {
                'Access-Control-Allow-Origin' : '*',
            },
            'body': json.dumps(data)
        }
    
    def sanitize(item):
        item['dreg'] = item['dreg'].rstrip('\r\n')
    
        return item
    

    JSON对象是:

    [{"reg": "29-Oct-18", "dreg": "31-Dec-99", "stat": "R", "num": "xob13020"}, {"reg": "29-Oct-18", "dreg": "31-Dec-99", "stat": "R", "num": "oxb03873"}]
    

    (a、b、c、d)

    2 回复  |  直到 6 年前
        1
  •  2
  •   user234461    6 年前

    只要用正确的键名创建一个新的dict。例如。:

    [ { (k+'1') : v for k,v in sanitize(item).items() } for item in response['Items']]

    (但也许可以选择一个更好的命名约定………)

        2
  •  1
  •   Keerthana Prabhakaran    6 年前

    首先将json加载到dict

    >>> jsonobj = '[{"reg": "29-Oct-18", "dreg": "31-Dec-99", "stat": "R", "num": "xob13020"}, {"reg": "29-Oct-18", "dreg": "31-Dec-99", "stat": "R", "num": "oxb03873"}]'
    >>> import json
    >>> json.loads(jsonobj)
    [{u'stat': u'R', u'num': u'xob13020', u'reg': u'29-Oct-18', u'dreg': u'31-Dec-99'}, {u'stat': u'R', u'num': u'oxb03873', u'reg': u'29-Oct-18', u'dreg': u'31-Dec-99'}]
    >>> listdata = json.loads(jsonobj)
    

    >>> [item for item in listdata]
    [{u'stat': u'R', u'num': u'xob13020', u'reg': u'29-Oct-18', u'dreg': u'31-Dec-99'}, {u'stat': u'R', u'num': u'oxb03873', u'reg': u'29-Oct-18', u'dreg': u'31-Dec-99'}]
    >>> [{key:value for key,value in item.iteritems()} for item in listdata]
    [{u'stat': u'R', u'num': u'xob13020', u'reg': u'29-Oct-18', u'dreg': u'31-Dec-99'}, {u'stat': u'R', u'num': u'oxb03873', u'reg': u'29-Oct-18', u'dreg': u'31-Dec-99'}]
    

    通过字典数据结构中的键映射,

    >>> key_value_map = {'stat': 'c', 'num': 'd', 'reg': 'a', 'dreg': 'b'}
    

    您可以更改键值!

    >>> [{key_value_map[key]:value for key,value in item.iteritems()} for item in listdata]
    [{'a': u'29-Oct-18', 'c': u'R', 'b': u'31-Dec-99', 'd': u'xob13020'}, {'a': u'29-Oct-18', 'c': u'R', 'b': u'31-Dec-99', 'd': u'oxb03873'}]