2

I have a json list that looks like this:

{
    "callback": [{
            "id": "R_puFk4fZ8m1lE4bD",
            "set": "Default Response Set",
            "ace": "asdf",
            "date": "asdfdsa",
            "1": "asdf",
            "2": "s",
            "3": "3",
            "4": "1",
            "zone": "0",
            "long": "33.564498901367",
            "lat": "-112.00869750977"
        }
    ]
}

My actual data has a lot of json objects within the list and I am wondering how I would put the numbers between "date" and "zone" in a separate list within the json. The numbers vary between the json objects, but they are always in between the "date" and "zone" values.

What would I do to transform it into this:

{
    "callback": [{
            "id": "R_puFk4fZ8m1lE4bD",
            "set": "Default Response Set",
            "ace": "asdf",
            "date": "asdfdsa",
            "Q": [
                "1": "asdf",
                "2": "s",
                "3": "3",
                "4": "1"
            ],
            "zone": "0",
            "long": "33.564498901367",
            "lat": "-112.00869750977"
        }
    ]
}
14
  • 6
    Note: Nothing is "always between 'date' and 'zone'" because that is equivalent to a Python dictionary and the ordering is not guaranteed. Are they the only keys that are numeric (represented as strings)? Commented Jul 18, 2017 at 18:40
  • @roganjosh Oh okay, thank you. They are keys represented as strings, but not all of the callbacks are numeric representations of strings, some are just strings. Commented Jul 18, 2017 at 18:43
  • 1
    ok... maybe you could go the other way round. Barring those keys that you want to capture, is the list of keys you don't want to capture always the same? Commented Jul 18, 2017 at 18:56
  • 2
    Are all the rest of the fields static and the dynamic fields are the ones you want to group? if key not in ["id", "set", "ace", "date", ..., "lat"]: Commented Jul 18, 2017 at 19:00
  • 2
    Good idea @TemporalWolf, although it'd be more efficient to use a set rather than a list. Commented Jul 18, 2017 at 19:02

2 Answers 2

2

You can sort them out via set membership (as PM 2Ring mentioned, set membership is faster O(1)):

def group_questions(source_dct):
    meta_tags = {"id", "set", "ace", "date", "zone", "long", "lat"}

    result_dct = {"Q": {}}
    for key in source_dct:
        if key not in meta_tags:
            result_dct["Q"][key] = source_dct[key]
        else:
            result_dct[key] = source_dct[key]
    return result_dct

Result (note dictionaries are not ordered):

>>> print group_questions(dct)
{'set': 'Default Response Set', 
 'ace': 'asdf', 
 'zone': '0', 
 'long': '33.564498901367', 
 'Q': {'1': 'asdf', 
       '3': '3', 
       '2': 's', 
       '4': '1'}, 
 'lat': '-112.00869750977', 
 'date': 'asdfdsa', 
 'id': 'R_puFk4fZ8m1lE4bD'}
Sign up to request clarification or add additional context in comments.

Comments

1

Use the built-in int() function to check for integer keys:

new_list = []
for old_data in old_list: #old_list is the value of 'callback' key
    data = {'Q': {}}
    for key in old_data.keys():
        try:
            num = int(key)
            data['Q'][key] = old_data[key]
        except ValueError: # stringy keys
            data[key] = old_data[key]
    new_list.append(data)

Now, printing new_list using something like json.dumps() will give something like:

[
    {
        "Q": {
            "1": "asdf",
            "2": "s",
            "3": "3",
            "4": "1"
        },
        "id": "R_puFk4fZ8m1lE4bD",
        "set": "Default Response Set",
        "ace": "asdf",
        "date": "asdfdsa",
        "zone": "0",
        "long": "33.564498901367",
        "lat": "-112.00869750977"
    }
]

7 Comments

This assumes Q should contain all elements whose key is an int. This may or may not satisfy the OP.
@TemporalWolf No it doesn't do that. Q has string keys. See my output.
Thank you for the response, but as TemporalWolf said not all of the keys that I need to capture are integers.
@jdoe I'm sorry but do you mean that there are keys other that just "numbers" you want in Q?
@jdoe Oh I understand your point. So you originally wanted to separate the keys which were being displayed between the date and zone keys.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.