0

I am extracting some data from my JSON file placed locally on my PC: and structure is:

JSON DATA SAMPLE

{ "totalRecords": 1, 
  "items": [{
            "name": "Services Ltd",
            "country": "GB",
            "city": "Evesham",
            "zip": "WR11 1BY",
            "address": "Northwick House\r\rCoopers Lane"
      }]
}

Python Script

import json
from pprint import pprint
fileName = r'naturesmenu.json'
with open(fileName, 'r') as f:
    data = json.load(f)    
dataData = data["items"]
c = 1
for i in dataData:
    # pprint(i)
    name = i['name']
    address = i['address']
    print(address)

for:

address = i['address']

Output should be:

Northwick House\r\rCoopers Lane

or if it removes/ has the effect of carriage return then output should look like this:

Northwick House

Coopers Lane

but I'm getting only this output:

Coopers Lane

not the full value corresponding to address. What am I doing wrong can someone point out? thanks

Barmar
  • 741,623
  • 53
  • 500
  • 612
GigaByte
  • 700
  • 6
  • 21

2 Answers2

3

Carriage return without newline goes to the beginning of the line and then starts overwriting the same line, it doesn't go to the next line. So Coopers Lane is being displayed over Northwick House, and the output you'll see is

Coopers Laneuse

Change the JSON file so it contains \n instead of \r, that's a newline escape sequence.

Barmar
  • 741,623
  • 53
  • 500
  • 612
1

You can choose replace

dataData = data["items"]
c = 1
for i in dataData:
    # pprint(i)
    name = i['name']
    print(name)
    address = i['address'].replace('\r',' ')
    print(address)

# 'Northwick House Coopers Lane'

Or, \n in replace if you want output in new line

address = i['address'].replace('\r','\n')

# Northwick House
# Coopers Lane
meW
  • 3,832
  • 7
  • 27
  • yeah, the concept explained by @Barmer sir. confused about of whom answer should I accept. The above one explained well and this is corrected before that. – GigaByte Dec 02 '18 at 21:50