Why does python generate a string json file? - python

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.

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)

Challenge with cleaning up JSON and export into JSONL

Breaking my brain on following challenge ..
Trying to clean up JSON sample data and trying to export it to a JSONL file.
Org JSON file:
{"data": {"allSites": {"activeSys": 123, "totalSys": 24718}},
"sites": [{"accountId": "12345", "accountName": "system_a"},
{"accountId": "67890","accountName": "system_b"}]}
Required JSONL data format:
{"accountId": "12345", "accounName": "system_a"}
{"accountId": "67890", "accounName": "system_b"}
You can use ast.literal_eval conversion as an
intermediate step in order to extract the desired part and then use json.dumps to convert to a pretty format for newly created json object such as
import json
import ast
Js= """{"data": {"allSites": {"activeSys": 123, "totalSys": 24718}},
"sites": [{"accountId": "12345", "accountName": "system_a"},
{"accountId": "67890","accountName": "system_b"}]}"""
data = ast.literal_eval(Js)
newJs = data["sites"]
updatedJs = json.dumps(newJs, indent=4)
print(updatedJs)
if you want to read from a file(json.file) and write to another file(data_new.json), then use
import json
import ast
with open('data.json') as f, open('data_new.json', 'w') as f_out:
data = ast.literal_eval(f.read())
newJs = data["sites"]
f_out.write(format(newJs))

How to print number only from a .json file in 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

How can I do to modify this python script to get the same json file without the hightated section?

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 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'] }

Categories

Resources