Python Forum
Converting a json file to a dataframe with rows and columns
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Converting a json file to a dataframe with rows and columns
#10
That is not a json file. game-data is not valid json, and json syntax uses double quotes instead of single quotes. The file also looks like it is several individual json strings, not one data structure. Where did you get the file?

I'm going to guess that the file looks like this:
Output:
game-data [{'meta': {'user_id': '178054', 'level_id': 1}}] [{'meta': {'user_id': '178054', 'level_id': 1}}] [{'meta': {'user_id': '178054', 'level_id': 2}}]
Using that format, I wrote a program that skips the first line. For each following line it replaces single quotes with double quotes and does a json.loads() to get a python list of dictionaries. Then, thinking there is only one dictionary in the list, it gets the first dictionary and gets the values associated with the "meta" key. That information is collected into a list. Finally the json information is normalized and loaded into a dataframe.
import json
import pandas as pd

game_data = []
with open('data.txt', 'r') as file:
    next(file)
    for line in file:
        line = line.replace("'", '"')
        game_data.append(json.loads(line)[0]['meta'])

df = pd.json_normalize(game_data)
print(df)
Output:
user_id level_id 0 178054 1 1 178054 1 2 178054 2
Reply


Messages In This Thread
RE: Converting a json file to a dataframe with rows and columns - by deanhystad - Jan-29-2023, 02:26 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  encrypt data in json file help jacksfrustration 1 288 Mar-28-2024, 05:16 PM
Last Post: deanhystad
  Converting column of values into muliple columns of counts highland44 0 284 Feb-01-2024, 12:48 AM
Last Post: highland44
  Converting .txt to .csv file SunWers 21 12,338 Jan-20-2024, 10:03 AM
Last Post: Larz60+
  Create Choices from .ods file columns cspower 3 656 Dec-28-2023, 09:59 PM
Last Post: deanhystad
  parse json field from csv file lebossejames 4 803 Nov-14-2023, 11:34 PM
Last Post: snippsat
  Create csv file with 4 columns for process mining thomaskissas33 3 808 Nov-06-2023, 09:36 PM
Last Post: deanhystad
  Python Script to convert Json to CSV file chvsnarayana 8 2,612 Apr-26-2023, 10:31 PM
Last Post: DeaD_EyE
  Loop through json file and reset values [SOLVED] AlphaInc 2 2,218 Apr-06-2023, 11:15 AM
Last Post: AlphaInc
  Reading Specific Rows In a CSV File finndude 3 1,022 Dec-13-2022, 03:19 PM
Last Post: finndude
  How to properly format rows and columns in excel data from parsed .txt blocks jh67 7 1,964 Dec-12-2022, 08:22 PM
Last Post: jh67

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020