0

i've got a dot delimited string which I need to convert to Json. This is an example with different types of strings:

my.dictionary.value -> value
my.dictionary.list[0].value -> value
my.dictionary.list[1].value.list[0].value -> value

I have no problems converting the first type of string using a recursive approach:

def put(d, keys, item):
    if "." in keys:
        key, rest = keys.split(".", 1)
        if key not in d:
            d[key] = {}
        put(d[key], rest, item)
    else:
        d[keys] = item

But i'm struggling to find a solution for the lists. Is there a library that provides out of the box string to json conversion? Thank you for your time.

2 Answers 2

1

AFAIK, there isn't any modules that would do this

Here is a sample code to converted a series of dotted strings into json format. You just have create a new list when you see the pattern [n] in the string that would be used as a key.

import re
import json

def parse_dotted_strlines(strlines):
    res= {}
    for line in strlines.splitlines():
        parse_dotted_str(line, res)
    return res

def parse_dotted_str(s, res):
    if '.' in s:
        key, rest = s.split('.', 1)
        # Check if key represents a list
        match = re.search(r'(.*)\[(\d)\]$', key)
        if match:
            # List
            key, index = match.groups()
            val = res.get(key, {}) or []
            assert type(val) == list, f'Cannot set key {key} as of type list as i
t was earlier marked as {type(val)}'
            while len(val) <= int(index):
                val.append({})
            val[index] = parse_dotted_str(rest, {})
            res[key] = val
        else:
            # Dict
            res[key] = parse_dotted_str(rest, res.get(key, {}))
    elif '->' in s:
        key, val = s.split('->')
        res[key.strip()] = val.strip()

    return res                                                

Sample input and output

lines = """
my.dictionary.value -> value
my.dictionary.list[0].value -> value
my.dictionary.list[1].value.list[0].value -> value
"""

res = parse_dotted_strlines(lines)
print (json.dumps(res, indent=4))
{
    "my": {
        "dictionary": {
            "value": "value",
            "list": [
                {
                    "value": "value"
                },
                {
                    "value": {
                        "list": [
                            {
                                "value": "value"
                            }
                        ]
                    }
                }
            ]
        }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

the json package is what you need

import json
mydict = """{
    "str1": "str",
    "list1": ["list1_str1", "list1_str2"],
    "list2": ["list2_str1", "list2_str2", ["list2_str11", "list_str12"]]
}"""
json.loads(mydict)
>> {'str1': 'str',
 'list1': ['list1_str1', 'list1_str2'],
 'list2': ['list2_str1', 'list2_str2', ['list2_str11', 'list_str12']]}

5 Comments

You didn't read my question at all, I wasn't asking about how to dump a string
Yep, but I've updated my answer. I was doing the inverse :) . Is this what you need ?
No, I need to load a dot separated string as stated in the example :)
@Weizen can you please provide a minimal runnable example with its input and expected outputs ?
Looking at stackoverflow.com/questions/53270227/… I need a similar solution but the problem is that the solution stated there doesn't work with something like my.dictionary.list[0] -> value

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.