Use the json module to produce JSON output:
import json
with open(outputfilename, 'wb') as outfile:
json.dump(row, outfile)
This writes the JSON result directly to the file (replacing any previous content if the file already existed).
If you need the JSON result string in Python itself, use json.dumps() (added s, for 'string'):
json_string = json.dumps(row)
The L is just Python syntax for a long integer value; the json library knows how to handle those values, no L will be written.
Demo string output:
>>> import json
>>> row = [1L,[0.1,0.2],[[1234L,1],[134L,2]]]
>>> json.dumps(row)
'[1, [0.1, 0.2], [[1234, 1], [134, 2]]]'
Answer from Martijn Pieters on Stack OverflowUse the json module to produce JSON output:
import json
with open(outputfilename, 'wb') as outfile:
json.dump(row, outfile)
This writes the JSON result directly to the file (replacing any previous content if the file already existed).
If you need the JSON result string in Python itself, use json.dumps() (added s, for 'string'):
json_string = json.dumps(row)
The L is just Python syntax for a long integer value; the json library knows how to handle those values, no L will be written.
Demo string output:
>>> import json
>>> row = [1L,[0.1,0.2],[[1234L,1],[134L,2]]]
>>> json.dumps(row)
'[1, [0.1, 0.2], [[1234, 1], [134, 2]]]'
import json
row = [1L,[0.1,0.2],[[1234L,1],[134L,2]]]
row_json = json.dumps(row)
import json
array = '{"fruits": ["apple", "banana", "orange"]}'
data = json.loads(array)
print(data['fruits'])
# the print displays:
# ['apple', 'banana', 'orange']
You had everything you needed. data will be a dict, and data['fruits'] will be a list
Tested on Ideone.
import json
array = '{"fruits": ["apple", "banana", "orange"]}'
data = json.loads(array)
fruits_list = data['fruits']
print fruits_list
Now solution looks wired but this works and will be useful for you in optimization. Convert the complete list into str then remove all ' single commas with str function and the apply json loads, hurray this has got worked for me.
data = ['[1,2,3]', '[4,5,6]', '[7,8,9]']
r = str(data).replace("'",'')
import json
data = json.loads(r)
now your data will be of list of list without looping. You can achieve this.
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
ujson could make your code faster
import time
import json
import ujson
a_list = list(range(5000))
data = [str(a_list)] * 10000
s = time.time()
output = []
for item in data:
output.append(json.loads(item))
print("json : %s" % (time.time()-s))
s = time.time()
output = []
for item in data:
output.append(ujson.loads(item))
print("ujson : %s" % (time.time()-s))
On my PC...
json : 10.048374891281128
ujson : 6.533677577972412
def replace_empty_dict_with(d, value):
for k, v in d.iteritems():
if len(v) == 0:
d[k] = value
else:
replace_empty_dict_with(v, value)
d = {}
w = {}
for node, pid, _ in main_array:
if pid == -1:
w[node] = d[node] = {}
else:
parent = main_array[pid][0]
w[node] = w[parent][node] = {}
replace_empty_dict_with(d, -1)
import pprint
pprint.pprint(d)
output:
{'some_string0': {'some_string3': -1,
'some_string4': -1,
'some_string5': {'some_string9': {'some_string11': -1}}},
'some_string1': {'some_string6': -1, 'some_string7': {'some_string10': -1}},
'some_string2': {'some_string8': -1}}
I understood the task a bit differently. I thought some_random_int was supposed to become the value in the final dictionary (not necessarily -1).
main_json = {}
id_to_dict_reference = {
-1: main_json
}
id_to_container = {}
id_to_key_name = {}
for id, (var_some_string, parent_id, some_random_int) in enumerate(main_array):
id_to_key_name[id] = var_some_string
dict_reference = id_to_dict_reference[parent_id]
if dict_reference is None:
parent_container = id_to_container[parent_id]
key_name = id_to_key_name[parent_id]
if not isinstance(parent_container[key_name], dict):
parent_container[key_name] = {}
parent_container[key_name][var_some_string] = some_random_int
id_to_dict_reference[id] = None
id_to_container[id] = parent_container[key_name]
id_to_dict_reference[parent_id] = parent_container[key_name]
else:
dict_reference[var_some_string] = some_random_int
id_to_container[id] = dict_reference
id_to_dict_reference[id] = None
print main_json
output:
{'some_string0': {'some_string3': -1,
'some_string4': -1,
'some_string5': {'some_string9': {'some_string11': -1}}},
'some_string1': {'some_string6': -1, 'some_string7': {'some_string10': -1}},
'some_string2': {'some_string8': -1}}
As I understand, you want to create a dict from your list. If so, you can do it like this:
colormap = {x:'red' for x in myList}
Afterwards, you can save it in json format using json module (please see a relevant question Storing Python dictionaries and documentation).
You can use
fromkeysmethod in the dictionary, like thisprint {}.fromkeys(myArray, "set")Or you can use
ziplike thisprint dict(zip(myArray, ["set"] * len(myArray)))
Output
{'OZONE PARK': 'set', 'BROOKLYN': 'set', 'STATEN ISLAND': 'set', 'SOUTH OZONE PARK': 'set', 'JAMAICA': 'set'}
Take a look at the json module. More specifically the 'Decoding JSON:' section.
import json
import requests
response = requests.get() # api call
users = json.loads(response.text)
for user in users:
print(user['id'])
You can try like below to get the values from json response:
import json
content=[{
"username": "admin",
"first_name": "",
"last_name": "",
"roles": "system_admin system_user",
"locale": "en",
"delete_at": 0,
"update_at": 1511335509393,
"create_at": 1511335500662,
"auth_service": "",
"email": "adminuser@cognizant.com",
"auth_data": "",
"position": "",
"nickname": "",
"id": "pbjds5wmsp8cxr993nmc6ozodh"
}, {
"username": "chatops",
"first_name": "",
"last_name": "",
"roles": "system_user",
"locale": "en",
"delete_at": 0,
"update_at": 1511335743479,
"create_at": 1511335743393,
"auth_service": "",
"email": "chatops@cognizant.com",
"auth_data": "",
"position": "",
"nickname": "",
"id": "akxdddp5p7fjirxq7whhntq1nr"
}]
for item in content:
print("Name: {}\nEmail: {}\nID: {}\n".format(item['username'],item['email'],item['id']))
Output:
Name: admin
Email: adminuser@cognizant.com
ID: pbjds5wmsp8cxr993nmc6ozodh
Name: chatops
Email: chatops@cognizant.com
ID: akxdddp5p7fjirxq7whhntq1nr
You can achieve this by using built-in json module
import json
arrayJson = json.dumps([{"email": item} for item in pyList])
Try to Google this kind of stuff first. :)
import json
array = [1, 2, 3]
jsonArray = json.dumps(array)
By the way, the result you asked for can not be achieved with the list you provided.
You need to use python dictionaries to get json objects. The conversion is like below
Python -> JSON
list -> array
dictionary -> object
And here is the link to the docs https://docs.python.org/3/library/json.html
