How to print in new line after every 2 element
Question:
This is the json file:
{
"x": [
{
"CourseCode" : "FHSC1014",
"CourseName" : "MECHANICS"
},
{
"CourseCode" : "FHCT1024",
"CourseName" : "PROGRAMMING CONCEPT AND DESIGN"
}
]
}
I want to print it like this;
FHSC1014 MECHANICS
FHCT1024 PROGRAMMING CONCEPT AND DESIGN
This is what I tried:
with open("test.json", 'r+') as f:
data = json.load(f)
x = data['x']
for i in x:
for j in i:
print(j)
Answers:
you can get data like this:
with open("test.json", 'r') as f:
data = json.load(f)
x = data['x']
for i in x:
print(i['CourseCode'], i['CourseName'])
You can do this by unpacking the values as follows:
import json
with open('test.json') as f:
for d in json.load(f).get('x', []):
print(*d.values())
Output:
FHSC1014 MECHANICS
FHCT1024 PROGRAMMING CONCEPT AND DESIGN
import json
with open("test.json", 'r') as f:
data = json.load(f)
x = data['x']
for i in x:
print(i['CourseCode'], i['CourseName'])
The output
FHSC1014 MECHANICS
FHCT1024 PROGRAMMING CONCEPT AND DESIGN
looping logic can be modified like the below:
for i in x:
line=""
for j in i:
if len(line)>0:
line+="t"
line+=i[j]
print(line)
This is the json file:
{
"x": [
{
"CourseCode" : "FHSC1014",
"CourseName" : "MECHANICS"
},
{
"CourseCode" : "FHCT1024",
"CourseName" : "PROGRAMMING CONCEPT AND DESIGN"
}
]
}
I want to print it like this;
FHSC1014 MECHANICS
FHCT1024 PROGRAMMING CONCEPT AND DESIGN
This is what I tried:
with open("test.json", 'r+') as f:
data = json.load(f)
x = data['x']
for i in x:
for j in i:
print(j)
you can get data like this:
with open("test.json", 'r') as f:
data = json.load(f)
x = data['x']
for i in x:
print(i['CourseCode'], i['CourseName'])
You can do this by unpacking the values as follows:
import json
with open('test.json') as f:
for d in json.load(f).get('x', []):
print(*d.values())
Output:
FHSC1014 MECHANICS
FHCT1024 PROGRAMMING CONCEPT AND DESIGN
import json
with open("test.json", 'r') as f:
data = json.load(f)
x = data['x']
for i in x:
print(i['CourseCode'], i['CourseName'])
The output
FHSC1014 MECHANICS
FHCT1024 PROGRAMMING CONCEPT AND DESIGN
looping logic can be modified like the below:
for i in x:
line=""
for j in i:
if len(line)>0:
line+="t"
line+=i[j]
print(line)