简体   繁体   中英

Convert a String to Python Dictionary or JSON Object

Here is the problem - I have a string in the following format (note: there are no line breaks). I simply want this string to be serialized in a python dictionary or a json object to navigate easily. I have tried both ast.literal_eval and json but the end result is either an error or simply another string. I have been scratching my head over this for sometimes and I know there is a simple and elegant solution than to just write my own parser.

{
  table_name:

   {
     "columns":

   [
     {

        "col_1":{"col_1_1":"value_1_1","col_1_2":"value_1_2"},
        "col_2":{"col_2_1":"value_2_1","col_2_2":"value_2_2"},
        "col_3":"value_3","col_4":"value_4","col_5":"value_5"}],

     "Rows":1,"Total":1,"Flag":1,"Instruction":none

    }
}

Note, that JSON decoder expects each property name to be enclosed in double quotes.
Use the following approach with re.sub() and json.loads() functions:

import json, re

s = '{table_name:{"columns":[{"col_1":{"col_1_1":"value_1_1","col_1_2":"value_1_2"},"col_2":{"col_2_1":"value_2_1","col_2_2":"value_2_2"},"col_3":"value_3","col_4":"value_4","col_5":"value_5"}],"Rows":1,"Total":1,"Flag":1,"Instruction":none}}'
s = re.sub(r'\b(?<!\")([_\w]+)(?=\:)', r'"\1"', s).replace('none', '"None"')
obj = json.loads(s)

print(obj)

The output:

{'table_name': {'columns': [{'col_5': 'value_5', 'col_2': {'col_2_1': 'value_2_1', 'col_2_2': 'value_2_2'}, 'col_3': 'value_3', 'col_1': {'col_1_2': 'value_1_2', 'col_1_1': 'value_1_1'}, 'col_4': 'value_4'}], 'Flag': 1, 'Total': 1, 'Instruction': 'None', 'Rows': 1}}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM