Convert string to json [Python]

Asked

Viewed 889 times

-2

I have a case where I have a json(is like clob) in the database and I want to use it to make a post request and everything by python, but I have a problem at the time of converting this string to json. What happens is that all the " are transformed into ' and this is giving problem in the request, because he ends up understanding that the attributes of my object "father" are actually his values.

Ex: Original value:

{
    "contrato": {
        "atb1": "013128415879",
        "atb2": "20200109",
        "atb3": 0,
        "obj1": {
            "atb4": "182938",
            "atb5": "ABCD",
            "atb6": 3
        },
        "obj2": {
            "atb7": "100104353",
            "atb8": 25
        }
    }
}

Value after conversion(json.loads):

{
    'contrato': {
        'atb1': '013128415879', 
        'atb2': '20200109', 
        'atb3': 0, 
        'obj1': {
            'atb4': '182938', 
            'atb5': 'ABCD', 
            'atb6': 3
            }, 
        'obj2': {
            'atb7': '100104353', 
            'atb8': 25
        }
    }
}

And this structure comes to my service as follows:

{
    'contrato': [
        'atb1',
        'atb2',
        'atb3',
        'obj1',
        'obj2'
    ]
}

Can you tell me what I can do to get my service json correctly? I’m using the "requests" and "json" libraries".

The part of the code where I treat the value:

payload = str(result[3])#no result está uma linha do banco
payload = json.loads(payload) #aqui é onde faço a conversão para json

1 answer

0

Since you trust the source of the information (the string that contains json is always correct), can use this:

import json
import requests

json_string = """{
    "contrato": {
        "atb1": "013128415879",
        "atb2": "20200109",
        "atb3": 0,
        "obj1": {
            "atb4": "182938",
            "atb5": "ABCD",
            "atb6": 3
        },
        "obj2": {
            "atb7": "100104353",
            "atb8": 25
        }
    }
}"""


j = eval(json_string)
r = requests.post('www.url_to_send.com', json=j)
  • I was able to solve by changing information in the request, before I was passing as "date" after the URL instead of "json" as your example. Thank you so much for your help!!!

  • I’m glad I could help.:-)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.