0

I'm having a string like this :

{'4': {1, 2}, '2': {1, 2}, '0': {1, 2}}["eq('2', '0')", "eq('2', '4')", "eq('0','4')"]

And I only need everything before ["eq('2'.... so I only need to save {'4': {1, 2}, '2': {1, 2}, '0': {1, 2}} I cannot use index because the length can be different everytime so I have to somehow check for "[". Is there anyway in python to do this and then convert the result into json? I'm new to python so I'd appreciate any help.

4
  • 2
    "Is there anyway in python to do this" yes there is. str.split is your friend. "and then convert the result into json" Yep, there's a whole module for json Commented Aug 29, 2014 at 23:15
  • 1
    @AdamSmith: Except that the value given can't be directly encoded as JSON because it contains sets. Once you decide how you want to wrap the sets up in something JSON does include, it's not that hard, but until then it's impossible. Commented Aug 29, 2014 at 23:23
  • Why do you have two JSON serializations concatenated together? Regardless, any solution that doesn't involve a parser will be brittle because you're not tracking how deep you are in the object tree. Commented Aug 29, 2014 at 23:24
  • 1
    @DavidEhrmann: They're not valid JSON serializations; they're probably Python reprs. Commented Aug 29, 2014 at 23:28

1 Answer 1

1

If the format is actually this specific, it's pretty easy: just split on the [, because there are no [ parts inside the {…}. So:

>>> s = """{'4': {1, 2}, '2': {1, 2}, '0': {1, 2}}["eq('2', '0')", "eq('2', '4')", "eq('0','4')"]"""
>>> sd, _, sl = s.partition('[')
>>> sl = '[' + sl

Now, presumably you don't want to convert the string to JSON, but the dict that the string represents. To do that, you have to eval it. Because you've got nothing but displays full of literals, you can use the safe ast.literal_eval function to do that. So:

>>> import ast
>>> d = ast.literal_eval(sd)
>>> sd
"{'4': {1, 2}, '2': {1, 2}, '0': {1, 2}}"
>>> d
{'2': {1, 2}, '4': {1, 2}, '0': {1, 2}}

However, you still can't JSON-ify that, because {1, 2} is a set, and JSON doesn't do sets. You have to decide what you want to convert that into. An array? A dict with None values? Something else?


To turn all of the sets into lists (which can be rendered as JSON arrays), you have two choices.

The first is to subclass the JSONEncoder. There's a perfect example right near the top of the docs that does the same thing for encoding complex values as 2-element lists, which you should be able to adapt to your purposes easily: just change the complex to set, and the [o.real, o.imag] to list(o).

The second is to preprocess things. As with the initial parsing, how easy this is depends on how rigid your format is. If all of the top-level values of the dict are sets, and nothing else is a set, it's just {k: list(v) for k, v in sd.items()}. If, on the other hand, you have an arbitrary dict that recursively contains sets along with strings, numbers, dicts, and lists, then you'll probably want to write a recursive function to transform it.


Meanwhile… where did you get this data from? My guess is that you're got some other part of your code that's just printing out a dict (or f.write-ing a str() of a dict…) followed by a list. If so, instead of trying to recover that data later, you should change your code to write JSON (or something else parseable) in the first place.


If your format were a little bit less friendly—if the dict could have lists inside it—you'd need to do something fancier. For example, you could count up open braces minus close braces and keep going until you get back to 0, and that's the dict.

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

2 Comments

thanks for your help, let's say I want to change the {1,2} to array [1,2]. I'm sending this data to javascript so I need to iterate every item in the json object and read it's array
@HiradRoshandel: Edited the answer to explain.

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.