1

I am trying to convert a string to a dictionary using literal_eval(), the only issue I am facing here is I have a null in one of the dictionary values.

attributes = '{"New Value": "United States", "Old Value": null, "Reason": "lorem ipsum", "Source": "Action"}'

This is my input dict which I am casting into a string before passing to literal_eval(). when I do a literal eval using the code:

attributes_new = ast.literal_eval(attributes)

and I get this error when the code runs:

ValueError: malformed node or string: <ast.Name object at 0x1066efa30>

Is there a way I can replace this null with a None so that it doesn't fail or if there is a better and optimised solution, it is welcome. Thanks in advance.

3
  • 2
    "This is my input dict which I am casting into a string" What? Where are you doing that? What is producing the null? This looks like JSON. Why are you trying to use ast.literal_eval? Just use json.loads Apr 23, 2021 at 13:38
  • json.loads(attributes)?
    – Rakesh
    Apr 23, 2021 at 13:42
  • I just used json.loads and it seemed to work like a charm. Thanks a lot. Apr 23, 2021 at 13:45

2 Answers 2

2
attributes_new = ast.literal_eval(attributes.replace('null', 'None'))

...is what I'd do as it is simple and readable.


Edit: I just noticed it looks suspiciously a lot like JSON. Maybe use json.loads instead.

1
  • Yup, json.loads did work here. I was a bit skeptical first about using it, but now it makes sense to use that. Apr 23, 2021 at 13:47
1

You can use two method to solve this problem-

  • Using json package
    You can use direct jason.load pacakge as below to remove null
import json
attributes_None = json.loads(attributes)
  • Using ast package
    First you have to replace null with None
import ast
attributes = attributes.replace('null','None')
new_attributes = ast.literal_eval(attributes)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.