4

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
informatik01
16.5k11 gold badges82 silver badges112 bronze badges
asked Jul 2, 2014 at 12:11

2 Answers 2

7

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.

answered Jul 2, 2014 at 12:12
Sign up to request clarification or add additional context in comments.

Comments

2

Your string definition is invalid, you cannot use multiple lines and " quotes in a string delimited by just a single " quote. The following works:

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

as that uses triple-quoting.

You may want to consider using the json module instead to produce valid JSON, this reduces the chances for errors greatly:

import json
data = {
 'auth': {
 'tenantName': 'user1',
 'passwordCredentials': {
 'username': 'user1',
 'password': 'pass'
 }
 }
}
data = json.dumps(data)
answered Jul 2, 2014 at 12:13

1 Comment

I wouldn't even suggest him to write the JSON string manually inside a string... He might end up doing that instead of using json.dumps ;)

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.