0

I am looking to convert json with array, to array of jsons with key value pairs.

Below is the format I have. The index zero has three array of list with different values in it. The values of index zero should be represented in one single array with different json for each list as key value pair as shown below.

Example

{'0': ['ID:123,qty:2,name:zbc',
      'ID:234,qty:3,name:xyz',
      'ID:456,qty:6,name:opq']}

to be converted to

[{"ID":"123","qty":"2","name":"zbc"},{"ID":"234","qty":"3","name":"xyz"}{"ID":"456","qty":"6","name":"opq"}]

The whole data looks like below

{'0': ['ID:123,qty:2,name:zbc',
      'ID:234,qty:3,name:xyz',
      'ID:456,qty:6,name:opq']
'1':['ID:666,qty:2,name:ppp',
    'ID:322,qty:5,name:uuu'],
'2' : ['ID:333,qty:3,name:pqr',
      'ID:444,qty:5,name:mmm',
     'ID:555,qty:6,name:iii']
 }

Convert to as below:

[{"ID":"123","qty":"2","name":"zbc"}, 
 {"ID":"234","qty":"3","name":"xyz"}, 
 {"ID":"456","qty":"6","name":"opq"}]
 
[{"ID":"666","qty":"2","name":"ppp"}, 
 {"ID":"322","qty":"5","name":"uuu"}]

[ {"ID":"333","qty":"3","name":"pqr"}, 
  {"ID":"444","qty":"5","name":"mmm"}, 
  {"ID":"555","qty":"6","name":"iii"}]

Please help here.

3
  • What do you mean by ['ID:123,qty:2,name:zbc', ['ID:234,qty:3,name:xyz', ['ID:456,qty:6,name:opq'] ? 3 opening brackets, but only 1 closing bracket? This isn't even valid Python syntax. Commented Sep 13, 2021 at 10:17
  • Neither is your expected output, which is also invalid [{...}, {...} {...}] [{...} {...}] [{...} {...} {...}]. What is this? List of lists? Or 3 different lists? Commas aren't event present to mark separation between elements. Commented Sep 13, 2021 at 10:20
  • Sorry, I have edited the question,there were few errors. they are three different lists Commented Sep 13, 2021 at 10:27

2 Answers 2

1

Given this data:

data = {
    '0': [
        'ID:123,qty:2,name:zbc',
        'ID:234,qty:3,name:xyz',
        'ID:456,qty:6,name:opq'
    ],
    '1': [
        'ID:666,qty:2,name:ppp',
        'ID:322,qty:5,name:uuu'
    ],
    '2' : [
        'ID:333,qty:3,name:pqr',
        'ID:444,qty:5,name:mmm',
        'ID:555,qty:6,name:iii'
    ]
}

Solution 1:

Split each string by comma , to get each key-value pair and then by : to extract the key part and the value part.

data_list = []

for text_list in data.values():
    current_list = []
    for text in text_list:
        text_dict = {}
        for split in text.split(','):
            key, _, value = split.partition(':')
            text_dict[key] = value
        current_list.append(text_dict)
    data_list.append(current_list)

print(data_list)

Solution 2:

Use regex to transform each string into dictionary format. Then use ast.literal_eval() to convert it to dict.

import ast
import re

key_value_re = re.compile(r"(\w+):(\w+)")
data_list = [
    [
        ast.literal_eval("{" + key_value_re.sub(r'"\1":"\2"', text) + "}")
        for text in text_list
    ]
    for text_list in data.values()
]

print(data_list)

Output (both solutions):

[
    [
        {
            "ID": "123",
            "qty": "2",
            "name": "zbc"
        },
        {
            "ID": "234",
            "qty": "3",
            "name": "xyz"
        },
        {
            "ID": "456",
            "qty": "6",
            "name": "opq"
        }
    ],
    [
        {
            "ID": "666",
            "qty": "2",
            "name": "ppp"
        },
        {
            "ID": "322",
            "qty": "5",
            "name": "uuu"
        }
    ],
    [
        {
            "ID": "333",
            "qty": "3",
            "name": "pqr"
        },
        {
            "ID": "444",
            "qty": "5",
            "name": "mmm"
        },
        {
            "ID": "555",
            "qty": "6",
            "name": "iii"
        }
    ]
]
Sign up to request clarification or add additional context in comments.

Comments

0

This can be done with a combination of list and dictionary comprehension in a oneliner:

data = {'0': ['ID:123,qty:2,name:zbc',
      'ID:234,qty:3,name:xyz',
      'ID:456,qty:6,name:opq'],
'1':['ID:666,qty:2,name:ppp',
    'ID:322,qty:5,name:uuu'],
'2' : ['ID:333,qty:3,name:pqr',
      'ID:444,qty:5,name:mmm',
     'ID:555,qty:6,name:iii']
 }

[[{x.split(':')[0]:x.split(':')[1] for x in i.split(',')} for i in item] for item in data.values()]

Output:

[[{'ID': '123', 'qty': '2', 'name': 'zbc'},
  {'ID': '234', 'qty': '3', 'name': 'xyz'},
  {'ID': '456', 'qty': '6', 'name': 'opq'}],
 [{'ID': '666', 'qty': '2', 'name': 'ppp'},
  {'ID': '322', 'qty': '5', 'name': 'uuu'}],
 [{'ID': '333', 'qty': '3', 'name': 'pqr'},
  {'ID': '444', 'qty': '5', 'name': 'mmm'},
  {'ID': '555', 'qty': '6', 'name': 'iii'}]]

2 Comments

The index is not fixed , it varies it could grow upto 100000
That shouldn't pose a problem (as long as there are no nested values) as this solution only accesses the key and value pairs within the list items by index.

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.