I have a .js file with the following content:
AppSettings = {
projectName:'myproject',
url: 'https://www.google.com',
appKey: 'k2y-myproject_124439_18111',
newsKey: '',
version: moment().format('YYMMDD_HHmmss'),
mixpanelToken: '08e97bef3930f330037d9z6t56395060'
};
Which I would like to convert it into a python dictionary that I can access as follows
>>> print(data['AppSettings']['url']
>>> 'https://www.google.com'
What is the best way to achieve this?
Code
d = {'AppSettings':{}}
with open('tt.js', 'r') as f:
next(f)
for line in f:
splitLine = line.strip().replace(',','').split(':')
d['AppSettings'][splitLine[0]] = "".join(splitLine[1:])
d['AppSettings']['url']=d['AppSettings']['url'].replace('https//','https://')
d['AppSettings'].pop("}", None) #remove last item "}" from dict
print(d['AppSettings']['url'])
print(d['AppSettings']['newsKey'])
print(d['AppSettings']['appKey'])
print(d['AppSettings']['version'])
print(d['AppSettings']['mixpanelToken'])
Sample output
'https://www.google.com'
''
'k2y-myproject_124439_18111'
moment().format('YYMMDD_HHmmss')
'08e97bef3930f330037d9z6t56395060'
Related
I am trying to achieve the following json output:
My current code:
#!/usr/bin/env python3.9
import json
complete_lst = []
url_lst = ['https://', 'https://', 'https://']
complete_lst.append({'title': 'Hello'})
for url in url_lst:
complete_lst.append({'watch': {'Season1': {'url': url}}
})
with open("Hello.json", "w") as file:
json.dump(complete_lst, file)
the output json file looks like this :
I want all the urls to be nested under watch->Season1->url key
Try this:
import json
complete_lst = []
url_lst = ['https://', 'https://', 'https://']
complete_lst.append({
'title': 'Hello',
'watch': {'Season1':{"url":[]}}
})
for url in url_lst:
complete_lst[0]["watch"]["Season1"]["url"].append(url)
print(complete_lst)
If your data is static then just do that:
import json
complete_lst = [{
'title': 'Hello',
'watch': {'Season1':{"url":['https://', 'https://', 'https://']}}
}]
print(complete_lst)
Another way of doing this would be to build a dictionary instead of list:
#!/usr/bin/env python3.9
import json
url_lst = ['https://', 'https://', 'https://']
complete_list = {}
complete_list['title'] = "Hello"
complete_list['watch'] = {}
complete_list['watch']['Season1'] = {}
complete_list['watch']['Season1']['urls'] = []
for url in url_lst:
complete_list['watch']['Season1']['urls'].append(url)
with open("Hello.json", "w") as file:
json.dump(complete_list, file)
Note: Here you don't need to access item by their indices and can directly use keys
How can I extract the T3 Period, Year and maximum value?
file.json
[
{"Fecha":"2022-08-01T00:00:00.000+02:00", "T3_TipoDato":"Avance", "T3_Periodo":"M08", "Anyo":2022, "value":10.4},
{"Fecha":"2022-07-01T00:00:00.000+02:00", "T3_TipoDato":"Definitivo", "T3_Periodo":"M07", "Anyo":2022, "value":10.8},
{"Fecha":"2022-06-01T00:00:00.000+02:00", "T3_TipoDato":"Definitivo", "T3_Periodo":"M06", "Anyo":2022, "value":10.2}
]
My code:
import json
with open("file.json") as f:
distros_dict = json.load(f)
print (distros_dict)
that is my proposition.
Load data from a file to a list.
Loop thru every dict in a list to edit it.
(At my example I, deleted two keys from every dict in list.)
import json
distros_dict = []
with open(f'file.json', "r", encoding='utf-8') as f:
distros_dict.extend(json.load(f))
for item in distros_dict:
item.pop('Fecha')
item.pop('T3_TipoDato')
distros_dict = sorted(distros_dict, key = lambda i: i['value'], reverse=True)[0]
Try this:
from json import load
with open("file.json") as f:
dictionary_max = max(load(f), key=lambda x: x["value"])
result = {
"T3_Periodo": dictionary_max["T3_Periodo"],
"Anyo": dictionary_max["Anyo"],
"value": dictionary_max["value"],
}
print(result)
output:
{'T3_Periodo': 'M07', 'Anyo': 2022, 'value': 10.8}
I would like to write file with python
My code is producing:
{ date: 2018-11-28, weight: 172.91, height: 177.65, id:310 }
I want to have the following is the input inside the file
{ date: '2018-11-28', weight: 172.91, height: 177.65, id:310 }
With the single quote mark which I need it to be there.
Any help please for writing string into file with single quote mark ' .
my code:
my_dict = { 'date': '2018-11-28', 'weight': 172.91, 'height': 177.65, 'id':310 }
my_dict = str(my_dict)
f = open('file.txt', 'w')
f.write(my_dict)
f.close()
Thanks
Use the JSON library.
In your case you would use:
with open('file.txt', 'w') as f:
json.dump(my_dict, f, indent=4)
Or, to mimic your approach to files:
f = open('file.txt', w)
json.dump(my_dict, f, indent=4)
f.close()
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'] }
The following code is giving me the error:
Traceback (most recent call last): File "AMZGetPendingOrders.py", line 66, in <module>
item_list.append(item['SellerSKU']) TypeError: string indices must be integers
The code:
from mws import mws
import time
import json
import xmltodict
access_key = 'xx' #replace with your access key
seller_id = 'yy' #replace with your seller id
secret_key = 'zz' #replace with your secret key
marketplace_usa = '00'
orders_api = mws.Orders(access_key, secret_key, seller_id)
orders = orders_api.list_orders(marketplaceids=[marketplace_usa], orderstatus=('Pending'), fulfillment_channels=('MFN'), created_after='2018-07-01')
#save as XML file
filename = 'c:order.xml'
with open(filename, 'w') as f:
f.write(orders.original)
#ConvertXML to JSON
dictString = json.dumps(xmltodict.parse(orders.original))
#Write new JSON to file
with open("output.json", 'w') as f:
f.write(dictString)
#Read JSON and parse our order number
with open('output.json', 'r') as jsonfile:
data = json.load(jsonfile)
#initialize blank dictionary
id_list = []
for order in data['ListOrdersResponse']['ListOrdersResult']['Orders']['Order']:
id_list.append(order['AmazonOrderId'])
#This "gets" the orderitem info - this code actually is similar to the initial Amazon "get" though it has fewer switches
orders_api = mws.Orders(access_key, secret_key, seller_id)
#opens and empties the orderitem.xml file
open('c:orderitem.xml', 'w').close()
#iterated through the list of AmazonOrderIds and writes the item information to orderitem.xml
for x in id_list:
orders = orders_api.list_order_items(amazon_order_id = x)
filename = 'c:orderitem.xml'
with open(filename, 'a') as f:
f.write(orders.original)
#ConvertXML to JSON
amz_items_pending = json.dumps(xmltodict.parse(orders.original))
#Write new JSON to file
with open("pending.json", 'w') as f:
f.write(amz_items_pending)
#read JSON and parse item_no and qty
with open('pending.json', 'r') as jsonfile1:
data1 = json.load(jsonfile1)
#initialize blank dictionary
item_list = []
for item in data1['ListOrderItemsResponse']['ListOrderItemsResult']['OrderItems']['OrderItem']:
item_list.append(item['SellerSKU'])
#print(item)
#print(id_list)
#print(data1)
#print(item_list)
time.sleep(10)
I don't understand why Python thinks this is a list and not a dictionary. When I print id_list it looks like a dictionary (curly braces, single quotes, colons, etc)
print(data1) shows my dictionary
{
'ListOrderItemsResponse':{
'#xmlns':'https://mws.amazonservices.com/Orders/201 3-09-01',
'ListOrderItemsResult':{
'OrderItems':{
'OrderItem':{
'QuantityOrdered ':'1',
'Title':'Delta Rothko Rolling Bicycle Stand',
'ConditionId':'New',
'Is Gift':'false',
'ASIN':'B00XXXXTIK',
'SellerSKU':'9934638',
'OrderItemId':'49 624373726506',
'ProductInfo':{
'NumberOfItems':'1'
},
'QuantityShipped':'0',
'C onditionSubtypeId':'New'
}
},
'AmazonOrderId':'112-9XXXXXX-XXXXXXX'
},
'ResponseM etadata':{
'RequestId':'8XXXXX8-0866-44a4-96f5-XXXXXXXXXXXX'
}
}
}
Any ideas?
because you are iterating over each key value in dict:
{'QuantityOrdered ': '1', 'Title': 'Delta Rothko Rolling Bicycle Stand', 'ConditionId': 'New', 'Is Gift': 'false', 'ASIN': 'B00XXXXTIK', 'SellerSKU': '9934638', 'OrderItemId': '49 624373726506', 'ProductInfo': {'NumberOfItems': '1'}, 'QuantityShipped': '0', 'C onditionSubtypeId': 'New'}
so first value in item will be 'QuantityOrdered ' and you are trying to access this string as if it is dictionary
you can just do:
id_list.append(data1['ListOrderItemsResponse']['ListOrderItemsResult']['OrderItems']['OrderItem']['SellerSKU']))
and avoid for loop in dictionary
I guess you are trying to iterate OrderItems and finding their SellerSKU values.
for item in data1['ListOrderItemsResponse']['ListOrderItemsResult']['OrderItems']:
item_list.append(item['SellerSKU'])