Is there way to parse json data in python? [closed] - python

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 months ago.
Improve this question
import json
f = open('C:\Users\Hello\Desktop\usecase2.json',encoding = 'utf-8')
data = json.load(f)
print(data)
-Raw Data sheet contains the raw data to be parsed and arrange as per "Desired Output" sheet
-The number of iteration data for each Pur Lot is not same, however it is required to capture the entire raw da -you have to create a JSON file to capture entire data of Raw Data with the key as Pur Lot.
data
desired output

If you're looking to convert JSON (essentially text) to a python dict , then I would suggest you use this:
**
import json
# some JSON:
x = '{ "name":"John", "age":30, "city":"New York"}'
# parse x:
y = json.loads(x)
# the result is a Python dictionary:
print(y["age"])
**
then you can call y['keys'] = values to use data
here , y['name'] = "John"

Related

Extracting information from json file and then sorting using python [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
The Json file i want to extract "rank" information from
Basically I would like to get the top 10 ranks cryptocurrencies names.
each cryptocurrency has its rank in the given json screenshot.
is there anyway I can implement this in python?
Providing a link to the image shown
https://api.nomics.com/v1/currencies/ticker?key=demo-26240835858194712a4f8cc0dc635c7a
import requests
import json
resp = requests.get(url = "https://api.nomics.com/v1/currencies/ticker", params = {"key" :"demo-26240835858194712a4f8cc0dc635c7a"}) # Fetch response from API
resp = json.loads(resp.text)
final_names = []
for i in range(10): # JSON is ordered via Rank
final_names.append(resp[i]["name"])
print(final_names) # Print final names
Hope this answers your question!!!!
Solution if cryptocurrencies are not sorted by rank by default in your json:
import requests
from pprint import pprint
top_all = []
data = requests.get(url="https://api.nomics.com/v1/currencies/ticker",
params={"key": "demo-26240835858194712a4f8cc0dc635c7a"}).json()
for row in data:
top_all.append({"name": row["name"], "rank": row["rank"]})
top_all = sorted(top_all, key=lambda x: int(x["rank"]))
pprint(top_all[0:10])
Try this:
import json
# your saved json response from API
file_path = "full/path/to/file.json"
with open(file_path, "r") as f:
data = json.load(f)
top_10_names = [x["name"] for x in data[:10]]
# since the data is ordered by rank,
# you can take only the first 10 elements.
print(top_10_names)

Convert string structure in another [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I have a file with this pattern :
[account.invoice.set_num]
job_size = 0
trans_size = 100
[commission.invoice_second.create_full]
j_size = 0
[commission.invoice_principal.finalize]
j_size = 12
in_directory = /to/the/directory
I want to transform this pattern to a text like :
ACCOUNT_INVOICE_SET_NUM_JOB_SIZE = 0
ACCOUNT_INVOICE_SET_NUM_TRANS_SIZE = 100
COMMISSION_INVOICE_SECOND_CREATE_FULL_J_SIZE=0
COMMISSION_INVOICE_PRINCIPALE_FINALIZE_J_SIZE=12
COMMISSION_INVOICE_PRINCIPALE_FINALIZE_IN_DIRECTORY=/to/the/directory
I try to do that in Bash unix or in Python.
I don't konw what is the best/easiest way to do that.
It's quite feasible with config.ConfigParser features:
from configparser import ConfigParser
config = ConfigParser()
config.read('yourfile')
config_lines = ''
for section in config.sections():
s_key = section.replace('.', '_') # transformed section key
for k, v in config.items(section):
config_lines += f'{s_key}_{k}'.upper() + f'={v}\n'
print(config_lines)
The output:
ACCOUNT_INVOICE_SET_NUM_JOB_SIZE=0
ACCOUNT_INVOICE_SET_NUM_TRANS_SIZE=100
COMMISSION_INVOICE_SECOND_CREATE_FULL_J_SIZE=0
COMMISSION_INVOICE_PRINCIPAL_FINALIZE_J_SIZE=12
COMMISSION_INVOICE_PRINCIPAL_FINALIZE_IN_DIRECTORY=/to/the/directory

How to iterate over JSON array? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I have this JSON array with multiple roots:
[
{
"issuer_ca_id": 16418,
"issuer_name": "C=US, O=Let's Encrypt, CN=Let's Encrypt Authority X3",
"name_value": "sub.test.com",
"min_cert_id": 325717795,
"min_entry_timestamp": "2018-02-08T16:47:39.089",
"not_before": "2018-02-08T15:47:39"
},
{
"issuer_ca_id":9324,
"issuer_name":"C=US, O=Amazon, OU=Server CA 1B, CN=Amazon",
"name_value":"marketplace.test.com",
"min_cert_id":921763659,
"min_entry_timestamp":"2018-11-05T19:36:18.593",
"not_before":"2018-10-31T00:00:00",
"not_after":"2019-11-30T12:00:00"
}
]
I want to iterate over it and print issuer_name values in Python. Any solution, please?
Use the json package and load the json. Assuming it is a string in memory (as opposed to a .json file):
jsonstring = """
[
{
"issuer_ca_id": 16418,
"issuer_name": "C=US, O=Let's Encrypt, CN=Let's Encrypt Authority X3",
"name_value": "sub.test.com",
"min_cert_id": 325717795,
"min_entry_timestamp": "2018-02-08T16:47:39.089",
"not_before": "2018-02-08T15:47:39"
},
{
"issuer_ca_id":9324,
"issuer_name":"C=US, O=Amazon, OU=Server CA 1B, CN=Amazon",
"name_value":"marketplace.test.com",
"min_cert_id":921763659,
"min_entry_timestamp":"2018-11-05T19:36:18.593",
"not_before":"2018-10-31T00:00:00",
"not_after":"2019-11-30T12:00:00"
}
]"""
import json
j = json.loads(jsonstring)
[item["issuer_name"] for item in j]
Gives:
["C=US, O=Let's Encrypt, CN=Let's Encrypt Authority X3",
'C=US, O=Amazon, OU=Server CA 1B, CN=Amazon']
Now, these don't look like names to me, but that's what is assigned to the issuer_name field, so I think that's something you have to take up with the owner of the data.
If it's a file, you do the loading in this basic pattern:
# something like this
with open("jsonfile.json", "rb") as fp:
j = json.load(fp)
See the docs here: https://docs.python.org/3.7/library/json.html

Convert string to dictionary with counts of variables [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
This is a snippet of the output:
{...,"resultMap":
{..."SEARCH_RESULTS":
[{..."resultList":[
{"userClientId":"1"","preferenceValues":["48","51","94"],"MyDate":"7/26/2017 8:30:00 AM"},
{"userClientId":"2","preferenceValues":["42","11","84"],"MyDate":"7/26/2017 9:40:00 AM"},
{"userClientId":"3","preferenceValues":["4","16","24"],"MyDate":"7/26/2017 4:20:00 PM"},
{"userClientId":"4","preferenceValues":["7","2","94"],"MyDate":"7/27/2017 8:00:00 AM"},
{"userClientId":"1","preferenceValues":["48","22","94"],"MyDate":"7/27/2017 1:50:00 PM"},
{"userClientId":"2","preferenceValues":["42","11"],"MyDate":"7/27/2017 2:00:00 PM"},
{"userClientId":"3","preferenceValues":["4","24"],"MyDate":"7/27/2017 6:15:00 PM"},
{"userClientId":"4","preferenceValues":"7","MyDate":"7/27/2017 9:30:00 PM"}]
}]
}
}
I am looking to get a variable pageIdCount that is in dictionary format, where the key is page_id and the values are a counts of occurrences of page_id, by user_id. So for userId 1 it should look like:
{"userClientId":"1","preferenceValues":{48:2, 51:1, 94:2, 22:1}}
Note that when there is only 1 variable inside preferenceValues- there are no brackets. There is also a field "preferenceValue" where there are no brackets no matter what and it is identical to "preferenceValues" otherwise.
Is that possible?
In Python 2.7, I specify user, password and url and then I have the following:
req = requests.post(url = url, auth=(user, password))
ans = req.json()
print ["resultMap"]["SEARCH_RESULTS"][0]["resultList"]
Any help is greatly appreciated.
your_data # this is your data
final_data = {}
for line in yourdata:
uid = line["userId"]
pids = line["PageId"]
if uid not in final_data :
final_data[uid] = {}
for pid in pids :
pid = int(pid)
if pid not in final_data[uid]:
final_data[uid][pid]=0
final_data[uid][pid] += 1
res = [{"userId":uid,"PageIDCount":pids} for uid,pids in final_data.items()]
I suppose you are beginning, if so, the most tricky part of this code will probably be the last line, it uses list comprehension. here is a good lesson about it.

Tell me how to replace python data, How can I read the a.txt file and make it in the following format? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
Tell me how to replace python data
a.txt
abcd.com 0.0
* 6.6999306E7
asdf.com 1.50744025E8
asfd.df.com 1.93139033E8
fdsa.com 9.07938122E8
bank.com 2.638989462E9
fire.com 4.151822166E9
ms.com 7.026079907E9
How can I read the a.txt file and make it in the following format?
Output result :
['abcd.com', 0],
['*', 66999306],
['asdf.com', 150744025],
['asfd.df.com', 193139033],
['fdsa.com', 907938122],
['bank.com', 2638989462],
['fire.com', 4151822166],
['ms.com', 7026079907]
file = open('a.txt', 'r')
l = []
for line in file:
l.append( line.split())
Then if you want the second part to be integer, you can use list comprehension:
l = [ [i[0], int(float(i[1]))] for i in l]
output
[['abcd.com', 0],
['*', 66999306],
['asdf.com', 150744025],
['asfd.df.com', 193139033],
['fdsa.com', 907938122],
['bank.com', 2638989462],
['fire.com', 4151822166],
['ms.com', 7026079907] ]

Categories