1

I have the following sample data that are stored in a file:

[
  { "keys": ["val1", "val2"], "args": { "arg1": "val1", "arg2": "val2" } },
  { "keys": ["val1", "val2", "val3"], "args": { "arg": "val" } },
  { "keys": ["val"], "args": {} }
]

As you may realise, this is a list of dictionaries. Each dictionary has key keys contains arbitrary length of list and key args contains a dictionary

How could I parse this sample data back into Python object

with open('file_name') as file:
    source = file.read()

data = how_to_parse(source)

for arr in data:
    print(arr)

# Expected result
# { "keys": ["val1", "val2"], "args": { "arg1": "val1", "arg2": "val2" } }
# { "keys": ["val1", "val2", "val3"], "args": { "arg": "val" } }
# { "keys": ["val"], "args": {} }
2
  • Tks @AvinashRaj, that is correct answer. However as I am trying to learn pyparsing. I'd like to see an example using that library :) Commented Dec 21, 2015 at 8:24
  • Since your data looks like being JSON-formatted you might take a look at the json module. Commented Dec 21, 2015 at 8:36

1 Answer 1

1

The pyparsing wiki includes this example https://pyparsing.wikispaces.com/file/view/parsePythonValue.py/31712649/parsePythonValue.py which I implemented at a time when ast.literal_eval was not yet available. Using this code, your expression can be parsed using:

print listItem.parseString("""[
  { "keys": ["val1", "val2"], "args": { "arg1": "val1", "arg2": "val2" } },
  { "keys": ["val1", "val2", "val3"], "args": { "arg": "val" } },
  { "keys": ["val"], "args": {} }
]""")[0]

which gives:

[{'keys': ['val1', 'val2'], 'args': {'arg1': 'val1', 'arg2': 'val2'}}, 
 {'keys': ['val1', 'val2', 'val3'], 'args': {'arg': 'val'}}, 
 {'keys': ['val'], 'args': {}}]

There are many more examples at https://pyparsing.wikispaces.com/Examples for your self-edification.

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

3 Comments

This example is explained in more detail in this presentation ptmcg.com/geo/python/confs/TxUnconf2008Pyparsing.html - mouse over the lower-right corner to see the presentation navigation icons.
Thank you for your answer. It's great start for me to learn pyparsing
Pyparsing is no longer hosted on wikispaces.com. Go to github.com/pyparsing/pyparsing

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.