Parsing JSON in python for second object - python

I have a sample JSON in this format:
JSON FILE:
{
"Name": "ABC",
"Phone":"123",
"Address":[{"City":"City-1"},{"Country":"Country-1"}]
}
{
"Name": "ABC-1",
"Phone":"123-1",
"Address":[{"City":"City-2"},{"Country":"Country-2"}]
}
Is there any approach to parse the JSON and loop through the file and print each key-value pair.
The approach I used was through using
json_open = open(json_file)
json_data = json.load(json_open)
print(json_data[Name]) ##should give ABC
print(json_data[Name]) ##should give ABC-1 - unsure about the syntax and format
But I'm currently able to print only the first object values - i.e. name=ABC and not name=ABC-1

There is error in your json file. I modified your json and written code for traverse each element in it.
Error:
Error: Parse error on line 9:
... "Country-1" }]}{ "Name": "ABC-1",
-------------------^
Expecting 'EOF', '}', ',', ']', got '{'
sample.json
{
"data": [
{
"Name": "ABC",
"Phone": "123",
"Address": [
{
"City": "City-1"
},
{
"Country": "Country-1"
}
]
},
{
"Name": "ABC-1",
"Phone": "123-1",
"Address": [
{
"City": "City-2"
},
{
"Country": "Country-2"
}
]
}
]
}
sample.py
import json
json_file='sample.json'
with open(json_file, 'r') as json_data:
data = json.load(json_data)
jin=data['data']
for emp in jin:
print ("Name :"+emp["Name"])
print ("Phone :"+emp["Phone"])
print ("City :"+emp["Address"][0]["City"])
print ("Country :"+emp["Address"][1]["Country"])

Each record on json file is separated by ','. So, your file should look like:
[{
"Name": "ABC",
"Phone": "123",
"Address": [{
"City": "City-1"
}, {
"Country": "Country-1"
}]
},
{
"Name": "ABC-1",
"Phone": "123-1",
"Address": [{
"City": "City-2"
}, {
"Country": "Country-2"
}]
}
]
You can read the file and output as follows :
import json
my_file='test.json'
with open(my_file, 'r') as my_data:
data = json.load(my_data)
print data
for elm in data:
print elm['Phone']
print elm['Name']
print elm['Address'][0]['City']
print elm['Address'][1]['Country']

First of all this is not valid json format,
You can check here you json format
You should use this try.json file
{
"data":[{
"Name": "ABC",
"Phone":"123",
"Address":[{"City":"City-1"},{"Country":"Country-1"}]
}, {
"Name": "ABC-1",
"Phone":"123-1",
"Address":[{"City":"City-2"},{"Country":"Country-2"}]
}]
}
here is try.py
import json
json_open = open("try.json")
json_data = json.load(json_open)
for i in range(len(json_data['data'])):
print(json_data['data'][i]["Name"])
Note : python code is written in python3
output is look line this
ABC
ABC-1

Related

How to remove elements from json file using python?

I have a json file which looks like this
{
"name1": {
"name": "xyz",
"roll": "123",
"id": "A1"
},
"name2":{
"name": "abc",
"roll": "456",
"id": "A2"
},
"name3":{
"name": "def",
"roll": "789",
"id": "B1"
}
}
I want to remove name1, name2, name3 and should be looking like this
{
{
"name": "xyz",
"roll": "123",
"id": "A1"
},
{
"name": "abc",
"roll": "456",
"id": "A2"
},
{
"name": "def",
"roll": "789",
"id": "B1"
}
}
Is there any way to do this in python? If this problem is asked earlier then me please refer to one cause I can't find it. Help will be thankful.
Since you're expecting the outermost (root) level of json document to be an object (curly braces) you should specify at least one key to start with. Refer below example.
Python code Example
import json
in_file = open("/Input/path/to/sample.json", "r")
out_file = open("/Output/path/to/converted_json.json", "w")
input_json = json.load(in_file)
print(input_json)
converted_json = {"names": [input_json[key] for key in input_json]}
print(converted_json)
json.dump(converted_json, out_file)
in_file.close(), out_file.close()
Out put will be a json file with name converetd_json.json with below content.
{
"names": [{
"name": "xyz",
"roll": "123",
"id": "A1"
},
{
"name": "abc",
"roll": "456",
"id": "A2"
},
{
"name": "def",
"roll": "789",
"id": "B1"
}
]
}
If you want to avoid this root key, an alternative is to use an array (Square Brackets) as an outermost level. Refer below example.
Python Code
import json
in_file = open("/Input/path/to/sample.json", "r")
out_file = open("/Output/path/to/converted_json.json", "w")
input_json = json.load(in_file)
print(input_json)
converted_json = [input_json[key] for key in input_json]
print(converted_json)
json.dump(converted_json, out_file)
in_file.close(), out_file.close()
Out put will be a json file with name converetd_json.json with below content.
[
{
"name": "xyz",
"roll": "123",
"id": "A1"
},
{
"name": "abc",
"roll": "456",
"id": "A2"
},
{
"name": "def",
"roll": "789",
"id": "B1"
}
]
Note: The outermost level of a JSON document is either an "object" (curly braces) or an "array" (square brackets). So in this case both are valid json.
You can use simple python script. First, you need to read the json file and then load it as an json object. Then, you can iterate on the whole json object to change it to whatever format you need.
import json
with open("file.json","r+") as file:
s = file.read()
jfile = json.loads(s)
with open("ss.json","w") as file:
json.dump([jfile[i] for i in jfile], file)

Read nested Json File and fetch the required field

I have the following json file, Need to loop over to fetch the company and its file.
data.json
[
{
"count": 0,
"company": "abc",
"state": {
"city": {}
},
"name": "Techno",
"age": 17,
"file": "cubix.so"
},
{
"count": 12,
"company": "def",
"state": {
"city": {}
},
"name": "Uni",
"age": 17,
"file": "cyp.so"
},
{
"count": 22,
"company": "ghi",
"state": {
"city": {}
},
"name": "unicorn",
"age": 17,
"file": "omg.so"
}
]
Need to loops through json file and print the file with its company.
import json
import sys
f=open('data.json')
print(json.dumps(output))
Expected Output:
file with respect to company
Use json.loads() to load from JSON content and context managers while working with files:
import json
with open('data.json') as file:
data = json.loads(file.read())
for obj in data:
print(obj['company'], obj['file'])
Output:
abc cubix.so
def cyp.so
ghi omg.so
After reading the file, you could use json.load() to load the object, which is a list. Then you can iterate over the list and print the respective keys 'company' and 'file'
import json
f = open('data.json')
for e in json.load(f):
print(e['company'], e['file'])
f.close()
output
abc cubix.so
def cyp.so
ghi omg.so

Importing only particular json file data into the python script

empjson:
{
"emp1": {
"name":"abc",
"id":"123",
"home-add":"USA",
},
"emp2": {
"name": "def",
"id":"456",
"home-add":"Can",
},
"emp3": {
"name": "ghi",
"id": "789",
"home-add": "UK",
},
}
Python script
dbjson = open('empjson.json', 'r')
jsondata = dbjson.read()
obj = json.loads(jsondata)
print(obj)
print(obj.emp1['name'],True)
Question: I can print the complete employee data but how do I just print particular employee data?
When I try doing this, it says attribute error.
And on the line print (obj.emp1['name'], True) can I save this data in a string?

Convert json data to dictionary

I am trying to convert my json data into a dictionary with key the id of the json data. for example lets say i have the following json:
{
"id": "1",
"name": "John",
"surname": "Smith"
},
{
"id": "2",
"name": "Steve",
"surname": "Ger"
}
And i want to construct a new dictionary which includes the id as a key and save it into a file so i wrote the following code:
json_dict = []
request = requests.get('http://example.com/...')
with open("data.json", "w") as out:
loaded_data = json.loads(request.text)
for list_item in loaded_data:
json_dict.append({"id": list_item["id"], "data": list_item })
out.write(json.dumps(json_dict))
In the file i get the following output:
[{"data": {"id":"1",
"name":"John",
"Surname":"Smith"
}
},
{"data": {"id":"2",
"name":"Steve",
"Surname":"Ger"
}
},
]
Why the id is not included in my dict before data ?
I'm pretty sure you're looking at a ghost here. You probably tested wrong. It will go away when you try to create a minimal, complete, and verifiable example for us (i. e. with a fixed string as input instead of a request call, with a print instead of an out.write, etc).
This is my test in which I could not reproduce the problem:
entries = [
{
"id": "1",
"name": "John",
"surname": "Smith"
},
{
"id": "2",
"name": "Steve",
"surname": "Ger"
}
]
json_dict = []
for i in entries:
json_dict.append({"id":i["id"], "data": i})
json.dumps(json_dict, indent=2)
This prints as expected:
[
{
"id": "1",
"data": {
"id": "1",
"surname": "Smith",
"name": "John"
}
},
{
"id": "2",
"data": {
"id": "2",
"surname": "Ger",
"name": "Steve"
}
}
]
You could try this instead:
json_dict = []
with open('data.json', 'w) as f:
loaded_data = json.loads(request.text)
for list_item in loaded_data:
json_dict.append({list_item['id'] : list_item})

How to Fetch the value of any item from the JSON output in Python?

I have a function in python which is fetching the data in JSON format and I need to get the value of one item and store it in variable so I could use it another function
import requests
import json
import sys
def printResponse(r):
print '{} {}\n'.format(json.dumps(r.json(),
sort_keys=True,
indent=4,
separators=(',', ': ')), r)
r = requests.get('https://wiki.tourist.com/rest/api/content',
params={'title' : 'Release Notes for 1.1n1'},
auth=('ABCDE', '*******'))
printResponse(r)
getPageid = json.loads(r)
value = int(getPageid['results']['id'])
I am trying to get the value of id(160925) item in variable "value" so I could use it another function
Below is the JSON OUTPUT
{
"_links": {
"base": "https://wiki.tourist.com",
"context": "",
"self": "https://wiki.tourist.com/rest/api/content?title=Notes+for+1.1u1"
},
"limit": 25,
"results": [
{
"_expandable": {
"ancestors": "",
"body": "",
"children": "/rest/api/content/160925/child",
"container": "",
"descendants": "/rest/api/content/160925/descendant",
"history": "/rest/api/content/160925/history",
"metadata": "",
"operations": "",
"space": "/rest/api/space/Next",
"version": ""
},
"_links": {
"self": "https://wiki.tourist.com/rest/api/content/160925412",
"tinyui": "/x/5IaXCQ",
"webui": "/display/Next/Notes+for+1.1u1"
},
"extensions": {
"position": "none"
},
"id": "160925",
"status": "current",
"title": "Notes for 1.1u1",
"type": "page"
}
],
"size": 1,
"start": 0
} <Response [200]>
It looks like the "results" key in the JSON response corresponds to a list, so you'll want to index into that list to get a dict.
E.g. getPageid['results'][0]['id'] should return you the string value of the "id" key for the first object in the "results" list

Categories