Python Forum
TypeError: string indices must be integers
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
TypeError: string indices must be integers
#1
Hi guys,

i have two json files
code works fine for test1.json, but it gives "TypeError: string indices must be integers" error for test2.json

can you help me to fix it please?
thank you.

import json
import datetime
import contextlib
import pandas as pd

class Game:
    @classmethod
    def from_json(cls, json_record):
        game = cls()
        game.country = json_record["CN"]
        game.league = json_record["L"]
        game.date = datetime.datetime.fromtimestamp(json_record["S"])
        game.hometeam = None
        game.awayteam = None
        game.odds1 = None
        game.oddsX = None
        game.odds2 = None
        game.over = None
        game.gline = None
        game.under = None

        if game_a := json_record:
            with contextlib.suppress(IndexError):
                game.hometeam = game_a.get("O1")
            with contextlib.suppress(IndexError):
                game.awayteam = game_a.get("O2")
        if game_e := json_record.get("E"):
            with contextlib.suppress(IndexError):
                game.odds1 = game_e[0].get("C")
            with contextlib.suppress(IndexError):
                game.oddsX = game_e[1].get("C")
            with contextlib.suppress(IndexError):
                game.odds2 = game_e[2].get("C")
        if game_f := json_record.get("AE"):
            with contextlib.suppress(IndexError):
                game.over = game_f[1]["ME"][4].get("C")
            with contextlib.suppress(IndexError):
                game.gline = game_f[1]["ME"][4].get("P")
            with contextlib.suppress(IndexError):
                game.under = game_f[1]["ME"][5].get("C")
        return game
            
    def __str__(self):
        return ','.join(
            str(item) for item in (
                self.country, self.league, self.date, self.hometeam, self.awayteam,
                self.odds1, self.oddsX, self.odds2, self.over, self.gline, self.under))

with open("test2.json", encoding="UTF-8") as f:
    jsondata = json.load(f)

games = [Game.from_json(game) for game in jsondata["Value"] if "KLASK" not in game["L"] and "5x5" not in game["L"] and "Home (Goals)" not in game["O1"] and "(Statistics)" not in game["O1"] and "(3x3)" not in game["O1"]]

df=pd.DataFrame(games)
df.to_excel("test.xlsx")
print("Saved.")
Error:
Traceback (most recent call last): File "c:\Json2Excel\Convert_Json_to_Excel.py", line 52, in <module> games = [Game.from_json(game) for game in jsondata["Value"] if "KLASK" not in game["L"] and "5x5" not in game["L"] and "Home (Goals)" not in game["O1"] and "(Statistics)" not in game["O1"] and "(3x3)" not in game["O1"]] File "c:\Json2Excel\Convert_Json_to_Excel.py", line 52, in <listcomp> games = [Game.from_json(game) for game in jsondata["Value"] if "KLASK" not in game["L"] and "5x5" not in game["L"] and "Home (Goals)" not in game["O1"] and "(Statistics)" not in game["O1"] and "(3x3)" not in game["O1"]] TypeError: string indices must be integers

Attached Files

.json   test1.json (Size: 25.68 KB / Downloads: 47)
.json   test2.json (Size: 32.02 KB / Downloads: 53)
Reply
#2
the 2 files have different structure
in test1.json jsondata["Value"] is list of dicts
in test2.json jsondata["Value"] is a dict

in test2.json you probably want to work with jsondata["Value"]["G"]
I would advise to check test2.json because maybe it's bad format for some reason
deneme2 likes this post
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#3
sorry me guys
as @buran guessed, i downloaded wrong file as test2.json from original website.
exisiting code works fine.

sorry all once again.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  TypeError: string indices must be integers, not 'str' LEMA 2 2,516 Jun-12-2024, 09:32 PM
Last Post: LEMA
  tuple indices must be integers or slices, not str cybertooth 16 19,321 Nov-02-2023, 01:20 PM
Last Post: brewer32
  No matter what I do I get back "List indices must be integers or slices, not list" Radical 4 2,633 Sep-24-2023, 05:03 AM
Last Post: deanhystad
  boto3 - Error - TypeError: string indices must be integers kpatil 7 3,176 Jun-09-2023, 06:56 PM
Last Post: kpatil
  Response.json list indices must be integers or slices, not str [SOLVED] AlphaInc 4 9,150 Mar-24-2023, 08:34 AM
Last Post: fullytotal
  "TypeError: string indices must be integers, not 'str'" while not using any indices bul1t 2 6,039 Feb-11-2023, 07:03 PM
Last Post: deanhystad
  Error "list indices must be integers or slices, not str" dee 2 2,878 Dec-30-2022, 05:38 PM
Last Post: dee
  TypeError: string indices must be integers JonWayn 12 5,911 Aug-31-2022, 03:29 PM
Last Post: deanhystad
  TypeError: float() argument must be a string or a number, not 'list' Anldra12 2 6,762 Jul-01-2022, 01:23 PM
Last Post: deanhystad
  TypeError: list indices must be integers or slices, not range Anldra12 2 4,489 Apr-22-2022, 10:56 AM
Last Post: Anldra12

Forum Jump:

User Panel Messages

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