Home > front end >  When I attempt to create a JSON Object in Python, It errors, despite having validated the JSON Onlin
When I attempt to create a JSON Object in Python, It errors, despite having validated the JSON Onlin

Time:03-01

I believe that the issue is due to python formatting all ' to ", which would result in the error message which I recieved upon running the program. My Code is as follows:

import requests
import json
import pandas as pd
username = input('enter username here: ')
print('')
passw = input('enter password here: ')
mcpayload = {"agent": {"name": "Minecraft", "version": 1}, "username": "{}".format(username), "password": "{}".format(passw), "requestUser": "true"}
header = {"Content-Type": "application/json"}
logintoken = requests.post('https://authserver.mojang.com/authenticate', data = mcpayload, headers = header)
print(logintoken.text)
print('')
print(logintoken.json)
print('')
print(logintoken.content)

It returns this err message on run:

{"error":"JsonParseException","errorMessage":"Unrecognized token 'agent': was expecting (JSON String, Number, Array, Object or token 'null', 'true' or 'false')\n at [Source: (org.eclipse.jetty.server.HttpInputOverHTTP); line: 1, column: 7]"}

<bound method Response.json of <Response [400]>>

b'{"error":"JsonParseException","errorMessage":"Unrecognized token \'agent\': was expecting (JSON String, Number, Array, Object or token \'null\', \'true\' or \'false\')\\n at [Source: (org.eclipse.jetty.server.HttpInputOverHTTP); line: 1, column: 7]"}'

CodePudding user response:

The problem is that you are not sending json string but you are sending a python dictionary. you would need to convert it to json first then send it.

You will need to use json.dumps to convert dictionary object to json string.

header=json.dumps(header) #converting dict to json
mcpayload=json.dumps(mcpayload) #converting dict to json

The code should look like this:

import requests
import json
import pandas as pd
username = input('enter username here: ')
print('')
passw = input('enter password here: ')
mcpayload = {"agent": {"name": "Minecraft", "version": 1}, "username": "{}".format(username), "password": "{}".format(passw), "requestUser": "true"}
header = {"Content-Type": "application/json"}

header=json.dumps(header) #converting dict to json
mcpayload=json.dumps(mcpayload) #converting dict to json

logintoken = requests.post('https://authserver.mojang.com/authenticate', data = mcpayload, headers = header)
print(logintoken.text)
print('')
print(logintoken.json)
print('')
print(logintoken.content)

CodePudding user response:

If you want to send JSON, pass the JSON object via the kwarg json, not data:

logintoken = requests.post(
    'https://authserver.mojang.com/authenticate',
    json=mcpayload
)

Also, you can omit sending the custom header then, since requests.post() will automagically serialize the object for you and set appropriate headers.

  • Related