2

I have a simple json in Django. I catch the file with this command data = request.body and i want to convert it to pandas datarame

JSON:

{ "username":"John", "subject":"i'm good boy", "country":"UK","age":25}

I already tried pandas read_json method and json.loads from json library but it didn't work.

3
  • It didntt work! Commented Feb 9, 2017 at 8:11
  • if i send the JSON with this formation it works: [{ "username":"John", "subject":"i'm good boy", "country":"UK", "age":25 }] but i want to catch it without the array [] Commented Feb 9, 2017 at 8:20
  • Add your code so it will be easier to understand your problem. Commented Feb 9, 2017 at 9:25

2 Answers 2

2

You can also use pd.DataFrame.from_records() when you have json or dictonary

df = pd.DataFrame.from_records([ json ]) OR df = pd.DataFrame.from_records([ dict. ])

or

you need to provide iterables for pandas dataframe:

e.g. df = pd.DataFrame({'column_1':[ values ],'column_2':[ values ]})

Sign up to request clarification or add additional context in comments.

Comments

2

I think you need DataFrame constructor:

json = { "username":"John", "subject":"i'm good boy", "country":"UK", "age":25 }
print (pd.DataFrame(json, index=[0]))
   age country       subject username
0   25      UK  i'm good boy     John

Or:

print (pd.DataFrame([json]))
   age country       subject username
0   25      UK  i'm good boy     John

EDIT:

If input is file and get error:

s = pd.read_json('file.json')

ValueError: If using all scalar values, you must pass an index

is necessary add typ=Series and then convert Series.to_frame with transpose by T:

s = pd.read_json('file.json', typ='series')
print (s)
age                   25
country               UK
subject     i'm good boy
username            John
dtype: object

df = s.to_frame().T
print (df)
  age country       subject username
0  25      UK  i'm good boy     John

6 Comments

Ok, what is type(json) ?
It is interesting if work [{ "username":"John", "subject":"i'm good boy", "country":"UK", "age":25 }] - I think with pd.DataFrame(json). But without [] you need pd.DataFrame([json]) - added [] to variable json
it is a simple json that every web platform use to send information to one webservice to another. I use POST method to send it and catch it. What do you mean with what type(json)??? If i use this command my web service doesnt return anython.
@jezrael it returns me just '0'. it doesn't work properly.
Sorry, I try explain more. I am not django user, but if assign output to variable x by x = some code what return json there is possible use type(x)
|

Your Answer

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.