How to print number only from a .json file in python - python

I want to print only the number from "PresentValue". But only from "ObjectIdentifier" : 1
I need to be able to specify what "ObjectIdentifier" that is going to be printed.
Here is my json file:
import json
# Data to be written
data = {
"AnalogValues": [
{
"ObjectIdentifier": 1,
"PresentValue": 10.2
},
{
"ObjectIdentifier": 2,
"PresentValue": 20.3
}
]
}
# Serializing json
json_object = json.dumps(data, indent = 4)
# Writing to sample.json
with open("AnalogValues.json", "w") as outfile:
outfile.write(json_object)
This is what I have tried so far (returns the whole json file):
import json
# Opening JSON file
with open('AnalogValues.json', 'r') as openfile:
# Reading from json file
json_object = json.load(openfile)
print(json_object)
print(type(json_object))

You can use function like this:
def get_present_value(no):
for a in data['AnalogValues']:
if a['ObjectIdentifier'] == int(no):
return a['PresentValue']
return None
print(get_present_value(2))
Output:
20.3

Related

Returning JSONDecodeError: Expecting value

I'm trying to open and print my json file but its returning
JSONDecodeError: Expecting value
This is my code
with open(input("Which json. file would you like to read? "),'r') as f:
weather = json.loads(f.read())
print(weather)
I really don't know whats the problem, all help appreciated!
This works for me:
import json
# Data to be written
dictionary = {
"name": "sathiyajith",
"rollno": 56,
"cgpa": 8.6,
"phonenumber": "9976770500"
}
# Serializing json
json_object = json.dumps(dictionary, indent=4)
with open("sample.json", "w") as outfile:
outfile.write(json_object)
with open(input("Which json. file would you like to read? "),'r', encoding='utf-8') as f:
weather = json.loads(f.read())
print(weather)

Why does python generate a string json file?

I would like to generate a json file from data retrieved in an api request and another json file. The problem is that in my generated json file, the braces are surrounded by double quotes and I also have "\n" and "\r" everywhere. Do you have a solution to generate a json file correctly?
A piece of my python code:
def write_json(data, filename='data.json'):
with open(filename, 'w', encoding='utf-8') as wf:
json.dump(data, wf, ensure_ascii=False, indent=4)
# JSON file to fetch IDs
with open('sast-projects.json', 'r', encoding='utf-8') as f:
projects = json.load(f)
with open('data.json') as json_file:
data = json.load(json_file)
temp = data['data']
for project in projects:
result_detail = requests.get(url_detail + str(project['id']), headers=header_detail)
temp.append(result_detail.text)
write_json(data)
And an example of my outpout (data.json):
{
"data": [
"{\r\n \"id\": 12,\r\n \"teamId\": 34,\r\n \"owner\": \"Some text\",\r\n \"name\": \"Some text\"\r\n }\r\n ]\r\n}",
"{\r\n \"id\": 98,\r\n \"teamId\": 65,\r\n \"owner\": \"Some text\",\r\n \"name\": \"Some text\"\r\n }\r\n ]\r\n}"
]
}
Change result_detail.text to result_detail.json(). You're trying to store the raw json string instead of a json object, which is causing double encoding issues.

Save a "pretty" JSON Object to disc with json.dump in Python

I try to save a "pretty" json object which I created from a pandas dataframe.
df = pd.read_csv("https://gist.githubusercontent.com/seankross/a412dfbd88b3db70b74b/raw/5f23f993cd87c283ce766e7ac6b329ee7cc2e1d1/mtcars.csv")
import json
d = df.to_dict(orient='records')
j = json.dumps(d, indent=2)
print(j)
The printed output looks great and when I copy it to an editor, it seems to work.
[
{
"model": "Mazda RX4",
"mpg": 21.0,
"cyl": 6,
"disp": 160.0,
"hp": 110,
"drat": 3.9,
"wt": 2.62,
"qsec": 16.46,
"vs": 0,
"am": 1,
"gear": 4,
"carb": 4
}
]
However, when I save it to disc, I does not look like expected.
with open("beispiel.json", "w") as write_file:
json.dump(j, write_file)
Everything is in one line and is not formatted at all:
"[\n {\n \"model\": \"Mazda RX4\",\n \"mpg\": 21.0,\n \"cyl\": 6,\n \"disp\": 160.0,\n
What am I doing wrong here?
The reason is that j is a string, so when you do:
with open("beispiel.json", "w") as write_file:
json.dump(j, write_file)
you are writing the string to the file. Just do:
json.dump(d, write_file, indent=2)
Try this:
import json
import pandas as pd
df = pd.read_csv("https://gist.githubusercontent.com/seankross/a412dfbd88b3db70b74b/raw/5f23f993cd87c283ce766e7ac6b329ee7cc2e1d1/mtcars.csv")
d = df.to_dict(orient='records')
# 1st form
with open("beispiel.json", "w") as write_file:
write_file.write(json.dumps(d, indent=2))
# or 2nd form
with open("beispiel.json", "w") as write_file:
json.dump(d, write_file, indent=2)

How to find all "Name" parameters from big Json data using python3

How can I extract all the names from big JSON file using Python3.
with open('out.json', 'r') as f:
data = f.read()
Here I'm opening JSON file after that I tried this
a = json.dumps(data)
b= json.loads(a)
print (b)
Here is my data from JSON file.
{"data": [
{"errorCode":"E0000011","errorSummary":"Invalid token provided","errorLink":"E0000011","errorId":"oaeZ3PywqdMRWSQuA9_KML-ow","errorCauses":[]},
{"errorCode":"E0000011","errorSummary":"Invalid token provided","errorLink":"E0000011","errorId":"oaet_rFPO5bSkuEGKNI9a5vgQ","errorCauses":[]},
{"errorCode":"E0000011","errorSummary":"Invalid token provided","errorLink":"E0000011","errorId":"oaejsPt3fprRCOiYx-p7mbu5g","errorCauses":[]}]}
I need output like this
{"oaeZ3PywqdMRWSQuA9_KML-ow","oaet_rFPO5bSkuEGKNI9a5vgQ","oaejsPt3fprRCOiYx-p7mbu5g"}
I want all errorId.
Try like this :
n = {b['name'] for b in data['movie']['people']['actors']}
If you want to get or process the JSON data, you have to load the JSON first.
Here the example of the code
from json import loads
with open('out.json', 'r') as f:
data = f.read()
load = loads(data)
names = [i['name'] for i in data['movie']['people']['actors']]
or you can change names = [i['name'] for i in data['movie']['people']['actors']] to Vikas P answers
Try using json module for the above.
import json
with open('path_to_file/data.json') as f:
data = json.load(f)
actor_names = { names['name'] for names in data['movie']['people']['actors'] }

Not getting expected output in python when converting a csv to json

I have an excel file in which data is saved in csv format in such a way.This data is present in the excel file as shown below,under column A (The CSV File is generated by LabView Software code which i have written to generate data).I have also attached an image of the csv file for reference at the end of my question.
RPM,Load Current,Battery Output,Power Capacity
1200,30,12,37
1600,88,18,55
I want to create a Json file in such format
{
"power_capacity_data" :
{
"rpm" : ["1200","1600"],
"load_curr" : ["30","88"],
"batt_output" : ["12","18"],
"power_cap" : ["37","55"]
}
}
This is my code
import csv
import json
def main():
#created a dictionary so that i can append data to it afterwards
power_data = {"rpm":[],"load_curr":[],"batt_output":[],"power_cap":[]}
with open('power1.lvm') as f:
reader = csv.reader(f)
#trying to append the data of column "RPM" to dictionary
rowcount = 0
for row in reader:
if rowcount == 0:
#trying to skip the first row
rowcount = rowcount + 1
else:
power_data['rpm'].append(row[0])
print(row)
json_report = {}
json_report['pwr_capacity_data'] = power_data
with open('LVMJSON', "w") as f1:
f1.write(json.dumps(json_report, sort_keys=False, indent=4, separators=(',', ': '),encoding="utf-8",ensure_ascii=False))
f1.close()
if __name__ == "__main__":
main()
The output json file that i am getting is this:(please ignore the print(row) statement in my code)
{
"pwr_capacity_data":
{
"load_curr": [],
"rpm": [
"1200,30,12.62,37.88",
"1600,88,18.62,55.88"
],
"batt_output": [],
"power_cap": []
}
}
The whole row is getting saved in the list,but I just want the values under the column RPM to be saved .Can someone help me out with what I may be doing wrong.Thanks in advance.I have attached an image of csv file to just in case it helps
You could use Python's defaultdict to make it a bit easier. Also a dictionary to map all your header values.
from collections import defaultdict
import csv
import json
power_data = defaultdict(list)
header_mappings = {
'RPM' : 'rpm',
'Load Current' : 'load_curr',
'Battery Output' : 'batt_output',
'Power Capacity' : 'power_cap'}
with open('power1.lvm', newline='') as f_input:
csv_input = csv.DictReader(f_input)
for row in csv_input:
for key, value in row.items():
power_data[header_mappings[key]].append(value)
with open('LVMJSON.json', 'w') as f_output:
json.dump({'power_capacity_data' : power_data}, f_output, indent=2)
Giving you an output JSON file looking like:
{
"power_capacity_data": {
"batt_output": [
"12",
"18"
],
"power_cap": [
"37",
"55"
],
"load_curr": [
"30",
"88"
],
"rpm": [
"1200",
"1600"
]
}
}

Categories

Resources