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
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
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)
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"}']
I must first preface this with the fact that I’m extremely new to python. Like just started learning it a little over a week ago.
I have been racking my brain over how to convert a json object I opened and loaded into a dictionary from a list so I can use the get() function nested within a for loop to do a student ID comparison from another json file (key name in that file is just ID).
Below is the command I’m trying to load the json file:
With open(‘file.json’) as x: object=json.load(x)
When I print(type(object)), it shows up as class list.
Here’s a sample of what the json looks like:
[
{
“Name”: “Steel”,
“StudentID”: 3458274
“Tuition”: 24.99
},
{
“Name”: “Joe”,
“StudentID”: 5927592
“Tuition”: 14.99
}
]
HELP! Thank you!
What you are looking to do is deserialize a json object to a class, I'm sure there are better answers than this one but here goes.
First Step: convert json array to python list
import json
# assuming it is a json object for now, you can loop through an do the same
json = {'completed': 0, 'content': 'do smtng', 'deadline': 'Mon, 22 Nov 2021 00:00:00 GMT', 'id': 4, 'user_id': 7}
job = json.loads(json)
Second Step: Converting our list to a class
There's not really a consensus here on how to do this. You can try libraries like attrs if your json is already formatted with the exact naming of your class, or you can do something manual like this:
import json
from dataclasses import dataclass
@dataclass
class Task:
completed: int
content: str
deadline: str
id: int
user_id: int
@classmethod
def from_dict(cls, dict):
return cls(completed=dict["completed"], content=dict["content"],
deadline=dict["deadline"], id=dict["id"],
user_id=dict["user_id"])
@classmethod
def from_json(cls, json_str: str):
return cls.from_dict(json.loads(json_str))
You can perform input validation here too if you want but trying to keep it basic
If you're ok with using external libraries, the simplest solution would be to use the builtin dataclasses module in Python 3.7+ along with the dataclass-wizard library for (de)serialization purposes.
Here's a simple enough example using data classes to model your data in this case. Note that I'm using a new feature, patterned date and time, to de-serialize a custom pattern string to a datetime object. If you want to keep the data as a string, you can annotate it just like deadline: str instead. I was able to use the format codes from the docs on datetime.
import json
from dataclasses import dataclass
from dataclass_wizard import fromlist, asdict, DateTimePattern
@dataclass
class Task:
completed: int
content: str
deadline: DateTimePattern['%a, %d %b %Y %H:%M:%S %Z']
id: int
user_id: int
list_of_dict = [
{'completed': 0, 'content': 'do smtng', 'deadline': 'Mon, 22 Nov 2021 00:00:00 GMT', 'id': 4, 'user_id': 7},
]
# De-serialize JSON data into a list of Task instances
list_of_tasks = fromlist(Task, list_of_dict)
print(list_of_tasks)
# Serialize list of Task instances
json_string = json.dumps([asdict(task) for task in list_of_tasks])
print(json_string)
Output:
[Task(completed=0, content='do smtng', deadline=datetime.datetime(2021, 11, 22, 0, 0), id=4, user_id=7)]
[{"completed": 0, "content": "do smtng", "deadline": "2021-11-22T00:00:00", "id": 4, "userId": 7}]
To make things a bit simpler, you can opt to subclass from the JSONWizard Mixin class. The main benefit here is a bunch of added helper class methods, like list_to_json which will serialize a list of dataclass instances to JSON, which seems like it could be useful in this case. This example is similar to the one above; note the output is the same in any case.
from dataclasses import dataclass
from dataclass_wizard import JSONWizard, DateTimePattern
@dataclass
class Task(JSONWizard):
completed: int
content: str
deadline: DateTimePattern['%a, %d %b %Y %H:%M:%S %Z']
id: int
user_id: int
list_of_dict = [
{'completed': 0, 'content': 'do smtng', 'deadline': 'Mon, 22 Nov 2021 00:00:00 GMT', 'id': 4, 'user_id': 7},
]
# De-serialize JSON data into a list of Task instances
list_of_tasks = Task.from_list(list_of_dict)
print(list_of_tasks)
# Serialize list of Task instances
json_string = Task.list_to_json(list_of_tasks)
print(json_string)
I am learning Python, and in particular, working with JSON and sqlite in Python. Ultimately I plan to use Python to load the JSON into a sqlite database.
Here is the question: Is there a way in to list all of the keys from a JSON file (not from a string) using Python? I want a list of all of the keys so I can determine what columns I will need/use in my sqlite table(s), without having to manually read the file and make a list.
BTW, this is something along the lines of using INFORMATION_SCHEMA.COLUMNS in SQL Server, or the FINDALL in Python for XML.
All of this is for personal learning, so I'm not looking to use other technologies, I'm sticking to Python, JSON, and sqlite on purpose.