I've got a long string. This string contains a list, like such example
'[{"ex1": 0, "ex2":1}, {"ex3": 2, "ex4":3}]'
I can use json5.loads
and then get the first element by using [0]
on the list, but json5.loads
takes a long time for longer strings. Is there a way to get just the first element without loading the entire list? (in this example it would be {"ex1": 0, "ex2":1}
. Splitting by commas doesn't work for me since there are commas contained in dictionaries in the list. Thanks.
Does your string work with
ast.literal_eval()
? If it does, you could doIf not, you could loop through the string character-by-character and yield any substring when the number of open-brackets are equal to the number of close-brackets.
If you want to parse the resulting substrings to objects, you could use
json5
like you already do, which is probably faster on the smaller string, or useast.literal_eval()