Python Skript mysql outt to json format

Gast #5025288
Lesenswert?

Hallo,
ich möchte gerne folgendes Skript zum laufen bringen
1
#!/usr/bin/python
2
# -*- coding: utf-8 -*-
3

4
import MySQLdb
5
import sys
6

7
try:
8
    con = MySQLdb.connect('localhost', 'xx', 'xxxx', 'xxxx')
9
    cur = con.cursor(MySQLdb.cursors.DictCursor)
10
    cur.execute("SELECT * FROM `PowerSystem`")
11

12
    rows = cur.fetchall()
13

14
    for row in rows:
15
        print row["ID"] + "_" + row["solarVoltage"]
16

17
except MySQLdb.Error, e:
18

19
    print "Error %d: %s" % (e.args[0], e.args[1])
20
    sys.exit(1)
21

22
finally:
23

24
    if con:
25
        con.close()

allerdings kommt immer de Fehler
1
Traceback (most recent call last):
2
  File "./mysql.py", line 15, in <module>
3
    print row["ID"] + "+" + row["solarVoltage"]
4
TypeError: unsupported operand type(s) for +: 'long' and 'str'


und danach möchte ich die ausgabe im print automatisch in json format

nach dem Format
1
{
2
    "1": {
3
        "solarVoltage": "xxxV"
4
    }, 
5
    "2": {
6
                "solarVoltage": "xxxV"
7
    }, 
8
    "3": {
9
        "solarVoltage": "xxxV"
10
    }
11
}


formatieren wie geht das?
Gast #5025477
Lesenswert?

Skriptanfänger schrieb:
>
1
> Traceback (most recent call last):
2
>   File "./mysql.py", line 15, in <module>
3
>     print row["ID"] + "+" + row["solarVoltage"]
4
> TypeError: unsupported operand type(s) for +: 'long' and 'str'
5
>

Tja: das eine Datenfeld enthält ein Integer, das andere einen String, 
die kannst Du nicht mit + konkatenieren. Du kannst stattdessen
1
print '%d+%s'%(row['ID'], row['solarVoltage'])

oder
1
print str(row['ID']) + '+' + row['solarVoltage']

benutzen.

> und danach möchte ich die ausgabe im print automatisch in json format
>
> nach dem Format
>
>
1
> {
2
>     "1": {
3
>         "solarVoltage": "xxxV"
4
>     },
5
>     "2": {
6
>                 "solarVoltage": "xxxV"
7
>     },
8
>     "3": {
9
>         "solarVoltage": "xxxV"
10
>     }
11
> }
12
>

Das kannst Du einfach umwandeln:
1
dumps( { x['ID']: {'solarVoltage': x['solarVoltage'] } for x in rows})

IMHO eleganteres JSON kommt aber vermutlich heraus, wenn Du es so 
machst:
1
dumps(map(dict, rows))
Gast #5026201
Lesenswert?

was sagt denn  /usr/bin/python --version ?

2.7 oder 3.X, mein verdacht ist da kommt 3.X raus dann ist das invalider 
Code. In den fall /usr/bin/python2 sagen oder besser das print so ändern 
das ist unter python3 gültig ist.
Gast #5026904
Lesenswert?

Dann zeig doch mal ein paar Zeilen um die Zeile 22 Rum vor allen 21 und 
davor. Die Syntax sieht erstmals korrekt aus. Vielleicht klammer 
vergessen oder ähnliches ein wenig weiter "oben" im Quelltext
Gast #5027265
Lesenswert?

Hallo
Hier das gesamte Skript

1
#!/usr/bin/python                                       
2
# -*- coding: utf-8 -*-                                 
3
                                                        
4
import MySQLdb                                          
5
import sys                                              
6
import json                                             
7
                                                        
8
try:                                                    
9
    rowes = []                                          
10
                                                        
11
    con = MySQLdb.connect('localhost', 'xxxx', 'xxxxxx'$
12
    cur = con.cursor(MySQLdb.cursors.DictCursor)        
13
    cur.execute("SELECT * FROM `PowerSystem`")          
14
                                                        
15
    rows = cur.fetchall()                               
16
                                                        
17
    for row in rows:                                    
18
        print '%d:%s'%(row['ID'], row['solarVoltage'])  
19
                                                        
20
                                                        
21

22
print json.dumps(map(dict, rows))                       
23
                                                        
24
except MySQLdb.Error, e:                                
25
                                                        
26
    print "Error %d: %s" % (e.args[0], e.args[1])       
27
    sys.exit(1)
Gast #5027548
Lesenswert?

Skriptanfänger schrieb:
> try:
> [...]
>     for row in rows:
>         print '%d:%s'%(row['ID'], row['solarVoltage'])
> [...]
> print json.dumps(map(dict, rows))

^^ das print muss auf die höhe des for (4 tabs einrücken) so ist es 
wirklich invalid da es innerhalb des try except ist. und die Einrückung 
tiefe bricht.


> except MySQLdb.Error, e:
>
>     print "Error %d: %s" % (e.args[0], e.args[1])
>     sys.exit(1)
Gast #5028627
Lesenswert?

Skriptanfänger schrieb:
> IndentationError: unindent does not match any outer inde
> ntation level

seufz steht doch da , python gefällt deine Einrückung nicht. Da wir 
wieder nur die Zeile haben. steht das Print exakt in der gleichen Tiefe 
wie das For  und das except in der nächsten Zeile exakt auf der des Try? 
Irgendwie so was wird es sein.

Antwort schreiben

Bitte melde dich an, um einen Beitrag zu schreiben.

oder

Mit Google-Account einloggen

Die Registrierung ist kostenlos und dauert nur eine Minute.

Jetzt registrieren