我有存儲在一個文件下面的示例數據:如何分析數據結構的這個字符串pyparsing
[
{ "keys": ["val1", "val2"], "args": { "arg1": "val1", "arg2": "val2" } },
{ "keys": ["val1", "val2", "val3"], "args": { "arg": "val" } },
{ "keys": ["val"], "args": {} }
]
正如你可能知道,這是一個dictionaries
list
。每個字典具有鍵keys
包含列表的任意長度和關鍵args
包含字典
如何可以解析該樣本數據回Python
對象
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": {} }
'ast.literal_eval' –
Tks @AvinashRaj,這是正確的答案。但是,因爲我正在嘗試學習'pyparsing'。我想看看使用該庫的示例:) – babygau
由於您的數據看起來像是JSON格式,因此您可以查看[json](https://docs.python.org/3/library/json)。 html)模塊。 – albert