0

I have a complex string with a nested dictionary in it. This dictionary further has a list of three similar dictionaries inside it. How do I convert this into a Python dictionary? Please help.

Input: 'name: "data dict" id: 2\nv6: false\nstats {\n hosts {\n cnt1: 256\n cnt2: 0\n }\n groups {\n cnt1: 1\n cnt2: 0\n }\n main_groups {\n cnt1: 1\n cnt2: 0\n }\n main_hosts {\n cnt1: 256\n cnt2: 0\n }\n}\n group_id: "None"'

Expected result: { name: "data dict", id: 2, v6: false, stats: { hosts: { cnt: 1, cnt: 2 } groups: { cnt: 1, cnt: 2 } main: { cnt: 1, cnt: 2 } main_hosts: { cnt: 1, cnt: 2 } } }

4
  • 3
    How did this string come to be??? This looks like it could have been a JSON at some point. Probably easiest to fix whatever is extracting this mess to extract the valid JSON... Commented Sep 18, 2017 at 19:06
  • 1
    I don't think I'd use a regex. I'm a fan of pyparsing for tasks like this. Commented Sep 18, 2017 at 19:06
  • can you show the string formatted, looks like a yaml, then yaml module will do conversion Commented Sep 18, 2017 at 19:06
  • you will need massage it into valid yaml (or json) by inserting semicolons before {, line break between " and space (comma for json) then use yaml (or json) module Commented Sep 18, 2017 at 19:12

2 Answers 2

1

As TS mentioned, there are a string with a nested dictionary (first time I interpret it as an implicit reference to validity). If the string content is valid JSON you can use json built-in package includes all you need to parse it:

import json
data = json.loads(your_string)

Read more in JSON package docs.

If not, you can write regular expression or use pyparsing package to process this string.

Sign up to request clarification or add additional context in comments.

5 Comments

This will not work because the original string is not properly formatted json
Look again, this will not work... the string is not valid JSON.
It is not valid JSON. Did you even try it?
oh, sorry, I miss this thing. I'll correct the answer in a minute
I've updated this with suggestions that covers both valid JSON or not. Still not sure isn't it better to remove the answer
0

With some editing of your input, it can be loaded by yaml and the data object is as you have requested it, a set of nested dictionaries. How was the input string created ?. The specific edits are :

  • change "data dict" id:" to "data dict"\nid:",
  • change "\n group_id" to "\ngroup_id"
  • change all { to : ,
  • remove all } .

Comments

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.