You can achieve this by using built-in json module
import json
arrayJson = json.dumps([{"email": item} for item in pyList])
Answer from ë.. on Stack OverflowYou 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
json - How to convert a list of numbers to jsonarray in Python - Stack Overflow
Convert JSON array to Python list - Stack Overflow
python - Convert a list to json objects - Stack Overflow
How to convert nested list into JSON?
Videos
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]]]'
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
Just adding onto alexce's response, you can easily convert the restructured data into JSON:
import json
json.dumps(result)
There are some potential security concerns with top-level arrays. I'm not sure if they're still valid with modern browsers, but you may want to consider wrapping it in an object.
import json
json.dumps({'results': result})
To solve this, you need to split the input list into chunks, by 7 in your case. For this, let's use this approach. Then, use a list comprehension producing a list of dictionaries:
>>> from pprint import pprint
>>> l = [['String 1'],['String 2'],['String 3'],['String 4'],['String 5'],
... ['String 6'],['String 7'],['String 8'],['String 9'],['String 10'],
... ['String 11']]
>>> def chunks(l, n):
... """Yield successive n-sized chunks from l."""
... for i in range(0, len(l), n):
... yield l[i:i+n]
...
>>>
>>> result = [{"title%d" % (i+1): chunk[i][0] for i in range(len(chunk))}
for chunk in chunks(l, 7)]
>>> pprint(result)
[{'title1': 'String 1',
'title2': 'String 2',
'title3': 'String 3',
'title4': 'String 4',
'title5': 'String 5',
'title6': 'String 6',
'title7': 'String 7'},
{'title1': 'String 8',
'title2': 'String 9',
'title3': 'String 10',
'title4': 'String 11'}]
I know that, list can be converted into JSON by using json.dumps(mylist).
But how can I convert something like this into JSON ?
[["abc", "bcd", "cde"] , ["pgr", "xyz"]]
decode JSON strings into dicts and put them in a list, last, convert the list to JSON
json_list = []
json_list.append(json.loads(JSON_STRING))
json.dumps(json_list)
or more pythonic syntax
output_list = json.dumps([json.loads(JSON_STRING) for JSON_STRING in JSON_STRING_LIST])
Use json.dumps before json.loads to convert your data to dictionary object This also helps prevent valueError: Expecting property name enclosed in double quotes.
Ex:
import json
myJSONStringList = ['{"user": "testuser", "data": {"version": 1, "timestamp": "2018-04-03T09:23:43.388Z"}, "group": "33"}',
'{"user": "otheruser", "data": {"version": 2, "timestamp": "2018-04-03T09:23:43.360Z", }, "group": "44"}']
print([json.loads(json.dumps(i)) for i in myJSONStringList])
Output:
[u'{"user": "testuser", "data": {"version": 1, "timestamp": "2018-04-03T09:23:43.388Z"}, "group": "33"}', u'{"user": "otheruser", "data": {"version": 2, "timestamp": "2018-04-03T09:23:43.360Z", }, "group": "44"}']
When you receive multiple JSON objects, those are in the form of a list (so between []). You could:
- covert JSON string to python dictionary using
json.loads() - filter using the dict
- dump dictionary into a JSON string using
json.dumps()
input = """[
{"document":
{"id": "1","image": "https://xxx.xxx.png","name": "xxx"}},
{"document":
{"id": "2","image": "https://xx2.xxx.png","name": "xx2"}}
]"""
input_dic = json.loads(input)
tmp = []
for item in input_dic:
tmp.append(json.dumps(item["document"]))
output = json.dumps(tmp)
print(output)
Hope I got your question.
It's not 100% clear what you have or what you want, but with a few assumptions (input is list of dict, desired output is list of dict):
json_obj = [
{
"document": {
"id": "1",
"image": "https://xxx.xxx.png",
"name": "xxx",
},
},
{
"document": {
"id": "2",
"image": "https://xx2.xxx.png",
"name": "xx2",
},
},
]
desired_output = [x["document"] for x in json_obj]
print(desired_output)
One by one access each element from list and put it into some dict and at the end append to a list:
import json
# some example lists
em_link = ['a', 'b', 'c']
em_title = ['x', 'y', 'z']
em_desc = [1,2,3]
arr = []
for i,j,k in zip(em_link, em_title, em_desc):
d = {}
d.update({"link": i})
d.update({"title": j})
d.update({"desc": k})
arr.append(d)
print(json.dumps(arr))
Output:
[{"link": "a", "title": "x", "desc": 1}, {"link": "b", "title": "y", "desc": 2}, {"link": "c", "title": "z", "desc": 3}]
This returns an array of JSON objects based off of Chandella07's answer.
from bs4 import BeautifulSoup
import pandas as pd
import requests
import json
r = requests.get("https://www.emojimeanings.net/list-smileys-people-whatsapp")
soup = BeautifulSoup(r.text, "lxml")
emojiLinkList = []
emojiTitleList = []
emojiDescriptionList = []
jsonData = []
for tableRow in soup.find_all("tr", attrs={"class": "ugc_emoji_tr"}):
for img in tableRow.findChildren("img"):
emojiLinkList.append(img['src'])
for tableData in soup.find_all("td"):
for boldTag in tableData.findChildren("b"):
emojiTitleList.append(boldTag.text)
for tableRow in soup.find_all("tr", attrs={"class": "ugc_emoji_tr"}):
for tabledata in tableRow.findChildren("td"):
if tabledata.has_attr("id"):
k = tabledata.text.strip().split('\n')[-1]
l = k.lstrip()
emojiDescriptionList.append(l)
for link, title, desc in zip(emojiLinkList, emojiTitleList, emojiDescriptionList):
dict = {"link": link, "title": title, "desc": desc}
jsonData.append(dict)
print(json.dumps(jsonData, indent=2))
Data Example:
{
"link": "https://www.emojimeanings.net/img/emojis/purse_1f45b.png",
"title": "Wallet",
"desc": "After the shopping trip, the money has run out or the wallet was forgotten at home. The accessory keeps loose money but also credit cards or make-up. Can refer to shopping or money and stand for femininity and everything girlish."
},