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)
Related
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.
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)
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
Currently, I'm trying to import a json file created by the following python script from a csv file.
import csv, json
csvFilePath ='USvideos.csv'
jsonFilePath = 'USvideos.json'
data = {}
with open(csvFilePath, encoding = 'utf8') as csvFile:
csvReader = csv.DictReader(csvFile)
for csvRow in csvReader:
video_id = csvRow['video_id']
data[video_id] = csvRow
with open(jsonFilePath, 'w') as jsonFile:
jsonFile.write(json.dumps(data, indent=4))
Problem statementThe problem is that I need to get a json file without the part in parenthesis by modifying the python script which it cames from
("2kyS6SvSYSE": ) {
"video_id": "2kyS6SvSYSE",
"trending_date": "17.20.11",
"title": "WE WANT TO TALK ABOUT OUR MARRIAGE"
},
("1ZAPwfrtAFY":) {
"video_id": "1ZAPwfrtAFY",
"trending_date": "17.20.11"
}
Purpose of solving it
I need to solve this because I want to import data appropriately in MongoDB
Guessing as to the output JSON format you need but can you give this a try?
import csv, json
csvFilePath ='USvideos.csv'
jsonFilePath = 'USvideos.json'
data = []
with open(csvFilePath, encoding = 'utf8') as csvFile:
csvReader = csv.DictReader(csvFile)
for csvRow in csvReader:
data.append(csvRow)
with open(jsonFilePath, 'w') as jsonFile:
jsonFile.write(json.dumps(data, indent=4))
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'] }