-4

I have a string which is of the form dictionary for sure. I need to parse it and store it as a dictionary in python.

What i have tried is this:

myObj={}
tmp=""
if ':' in line:
    key,value = line.split(':')
    key = key.strip('"')
    value = value.lstrip(' ').rstrip(',')
    if value == '{':
        tmp += key + '.'
    if value == '}':
        tmp = ''
    if(value!="{"):
        myObj[tmp + key] = value

Reading Line by Line and parsing it. But I am facing problems with different kind of formats.

For E.G.

        {
        "id": 1,
        "name": "Foo",
        "price": 123,
        "tags": [ "Bar", "Eek" ],
        "stock": {
            "warehouse": 300,
            "retail": 20
        }
    }

No use of eval or any built in function or library like json. Can I use regex here? How do I do this?

1 Answers1

2

You have JSON data, use the json library to parse it:

import json

data = json.loads(yourstring)

Python comes with batteries included, don't reinvent the wheel.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343