Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using JSN with Python

Tags:

python

json

I am trying to send JSON request using Python, but I receive an error when I try to create JSON object using the following format:

data="{
"auth": {
  "tenantName": "user1",
  "passwordCredentials": {
  "username": "user1",
  "password": "pass"
  }
 }
}"

The error message is:

File "auth.py", line 5
    data="{
          ^
SyntaxError: EOL while scanning string literal
like image 778
user2521791 Avatar asked Oct 21 '25 04:10

user2521791


1 Answers

You can simply create a dict and use json.dumps() to create a JSON string from it.

import json

data = json.dumps({
    'auth': {
        'tenantName': 'user1',
        'passwordCredentials': {
            'username': 'user1',
            'password': 'pass'
        }
    }
})

What you did is invalid since you can't have linebreaks in a "normal" quoted string - you'd have to use triple quotes instead. However, don't do that. Creating JSON using string functions is a bad idea, even if it's just dumpling a hand-crafted JSON string into a string.

like image 163
ThiefMaster Avatar answered Oct 23 '25 17:10

ThiefMaster



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!