2

I have been trying to fix this problem but I cannot. I have the following code:

import json

def jsonblock(filename):
    my_array = []
    with open(filename) as f:
        for line in f:
            my_array.append(line)
    p = " ".join(str(x) for x in my_array)
    return p;

for i in jsonblock('P5.json'):
    print(i) 

and my P5.json is

    {
  "signalPassed" : true,
  "location" : {
    "longitude" : 113.3910083760899,
    "latitude" : 22.57224988908558
  },
  "phoneOsVersion" : "7.0.3",
  "signalStdDev" : 4.139107,
  "phoneModel" : "iPad",
}

I want a normal output in str format but when I do it, I get the following output:

    "
7
.
0
.
3
"
,





"
s
i
g
n
a
l
S
t
d
D
e
v
"

:

4
.
1
3
9
1
0
7
,


}

Where is the problem? How can I fix this?

Mewto
  • 23
  • 3
  • 2
    `p` is being returned as a string try using `json.loads(filename)` and/or `json.dumps(filename)` – jmunsch Jun 24 '14 at 14:14
  • possible duplicate of [How to print in Python without newline or space?](http://stackoverflow.com/questions/493386/how-to-print-in-python-without-newline-or-space) – Upperstage Jun 24 '14 at 14:15
  • Why are you importing the `json` module and then never trying to use it? – Wooble Jun 24 '14 at 14:19

1 Answers1

6

Your function jsonblock returns a string, the result of ''.join(...). Iterating over a string produces individual characters, which you print out one by one in that for loop at the end.

To "solve" your immediate problem, just print jsonblock('P5.json') instead of using a for loop.

However, what you probably want to do is parse json correctly. In this case, use the json library that you already imported at the top.

filename = 'P5.json'
with open(filename, 'rb') as f:
    data = json.load(filename)
print data  # data is a dictionary in this case
davidism
  • 121,510
  • 29
  • 395
  • 339