-2

Sorry. I can not explain the details because I am not fluent in English.

I have a json document like this:

[
    {
        "id":"96103252",
        "pvname":"Bet365",
    }
]

My python code looks like this:

url_odds= cfg.oddsurl
oddsfeed = urllib2.urlopen(url_odds)
oddsjson = json.load(oddsfeed)
getjson = "{""data"":" + oddsjson + "}"

for sport in getjson["data"]:
   pv_id= validate(sport,"id")
   pv_name= validate(sport,"pv_name")
   sql= "INSERT INTO odds_sports(pv_id,pv_name) VALUES ('"
   sql= sql+ pv_id + "','"
   sql= sql+ pv_name + "')"
 cursor.execute(sql)
 conn.commit()

It sends this error


getjson = "{""data"":" + oddsjson + "}"

TypeError: cannot concatenate 'str' and 'list' objects

  • In order to do that you need to 'serialise' the list as a string first. Do these help? https://stackoverflow.com/questions/2147701/serializing-list-to-json Once you've serialised it you can concatenate it at your fourth line of code. – Nick.Mc Oct 29 '17 at 12:49
  • This says the same thing - use `dump` https://stackoverflow.com/questions/26033239/list-of-objects-to-json-with-python – Nick.Mc Oct 29 '17 at 12:50

1 Answers1

0

that's a very simple syntax error. in this line:

getjson = "{""data"":" + oddsjson + "}"

oddsjson is an array of dicts, you probably want to iterate over each element in it and parse the right value hence:

for sport in oddsjson:
   pv_id = validate(sport.get("id"))
   pv_name = validate(sport.get("pvname"))

also,

and on another issue. hand-writing SQL queries with strings you generate on the go is an invitation for troubles (especially when the query involves dynamic string generated by others). you better use some library like sqlalchemy as a middleware to your database.

akiva
  • 2,677
  • 3
  • 31
  • 40