0

I have a simple JSON file which is essentially a long string like this:

{"quickGang": {"scopeIds": [2,9],"name": "","channelIds": [],"enabled": false},"modelVersion": 0,"links": [],"applyOnConnect": false}

I am able to print out the contents of the file in separate lines as shown further down.

However when I attempt to work with the contents in a FOR loop, it is reading in each character at a time instead of each line.

How can I read a line at a time?

Here’s my code:

import os
import json

path="C:\\Users\\Mick T\\Downloads\\gangs.json"

with open(path, 'r') as json_file:
    file_name = os.path.basename(path)
    print (file_name)

    json_object = json.load(json_file)
    json_formatted_str = json.dumps(json_object, indent=2)

    print(json_formatted_str)

    i=1
    for line in json_formatted_str:
        print(line, ' ', end='')
        print (i)
        i = i + 1

Here’s the first part of the output with a counter included:-

C:\Users\Mick T\Downloads>python forum1.py
gangs.json
{
  "quickGang": {
    "scopeIds": [
      2,
      9
    ],
    "name": "",
    "channelIds": [],
    "enabled": false
  },
  "modelVersion": 0,
  "links": [],
  "applyOnConnect": false
}
{  1

  2
   3
   4
"  5
q  6
u  7
i  8
c  9
k  10
G  11
a  12
n  13
g  14
"  15
1
  • This is example of XY problem. I guess what you really ask is how to iterate over the nested dict, i.e. the content of json_object["quickGang"]. You must not dump it back into formatted string and iterate over it. Work with the dict you receive after you load the JSON. Otherwise what is the purpose of working with e.g. "scopeIds": [ line? Commented Oct 28 at 8:46

3 Answers 3

6

json_formatted_str.splitlines() will return a list of all of the lines.

In your case:

for line in json_formatted_str.splitlines():
   print(line)

This is probably the easiest solution.

Sign up to request clarification or add additional context in comments.

3 Comments

Most likely OP wants to iterate over content of the nested dict and work with the key, value pairs, rather than just printing nonsense like "scopeIds": [ line.
Then why would they turn the json object into a string?
That's a clear example of XY problem, they are trying to solve a problem using wrong approach, then ask question why their wrong approach is not working. The idea of line in JSON file does not have meaning. It's for mere representation/readability. It's not NDJSON/JSONLINE. As they state in the question However when I attempt to work with the contents in a FOR loop, i.e. they want to work with content of the json object/dict
3

json_formatted_str is a string, and iterating through a string will yield the individual characters. You probably want something like for line in json_formatted_str.split("\n")

4 Comments

Yes - or, even more simply, for line in json_formatted_str.splitlines().
Most likely OP wants to iterate over content of the nested dict and work with the key, value pairs, rather than just printing nonsense like "scopeIds": [ line.
Probably, but that's out of scope. If OP wants that they should say that. I don't think it's our place to infer what they really mean. Unless of course I'm missing a stackoverflow directive in which case I'm all ears
That's a clear example of XY problem, they are trying to solve a problem using wrong approach, then ask question why their wrong approach is not working. The idea of line in JSON file does not have meaning. It's for mere representation/readability. It's not NDJSON/JSONLINE. As they state in the question However when I attempt to work with the contents in a FOR loop, i.e. they want to work with content of the json object/dict
0

The issue is that in this line:

for line in json_formatted_str:

you're iterating over the string itself, which means Python goes character by character, not line by line.

The solution is to split the formatted JSON string into lines before iterating over it.

    for line in json_formatted_str.splitlines():
        print(line, ' ', end='')
        print(i)
        i += 1
  • json.dumps(..., indent=2) converts the JSON into a nicely formatted string.

  • .splitlines() splits that string into a list of lines (based on newline \n characters).

  • Now, for line in json_formatted_str.splitlines(): iterates over each line, not each character.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.