3

I have the Pandas DataFrame below and need to convert it to json format with the df.columns wrapped in a Django model name and "fields" fieldname. See below example of how the json should look. How should I do this?

df:

+-----------------+---------+------+
|     Artist      |  Title  | Year |
+-----------------+---------+------+
| Michael Jackson | Beat it | 1988 |
| Britney Spears  | Lucky   | 2012 |
| Justin Bieber   | Baby    | 2006 |
+-----------------+---------+------+

Json file output:

[
  {
    "model": "profiles.track",
    "fields": {
      "artist": "Michael Jackson",
      "title": "Beat it",
      "year": "1988",
    }
  },
  {
    "model": "profiles.track",
    "fields": {
      "artist": "Britney Spears",
      "title": "Lucky",
      "year": "2012",
    }
  },
  {
    "model": "profiles.track",
    "fields": {
      "artist": "Justin Bieber",
      "title": "Baby",
      "year": "2006",
    }
  }
]
3

1 Answer 1

1

We can convert the dataframe df to a list of dictionaries with:

df_dicts = df.T.to_dict().values()

But of course that does not give us fully the requested format, nor is this a JSON blob. But we can use this as a base to extend it. We can for example wrap every dictionary into another dictionary by performing a mapping:

result = list(map(lambda x: {'model': 'profiles.track', 'fields': x}, df_dicts))

Finally we can construct a JSON blob with:

import json

json_blob = json.dumps(result)

This will construct a string that is a JSON dump of result. We can for example print it with:

print(json_blob)
Sign up to request clarification or add additional context in comments.

Comments

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.