I try to split json data using data[1:], but don't work.
more concretely what I'm trying to do is ignore the first object array of a .json, but keep the rest in a variable
Py
f = open("people_data.json", "r")
data = json.load(f)
people = data[1:]
# irrelevant code
JSON
{
"variable_id": [
{
"name": "anybody",
"age": "25",
"job": "insurance company"
}
],
"Skills": [
{
"area": "programmer",
"level": "junior",
"comments": "..."
}
],
"other": [
{
"something": "..."
}
]
My goal is to have a variable with skills and others, but without personal data.
This is just an example, because the problem is that I don't know what will be the name of the following arrays because they will be variables instead of skills or other names
CodePudding user response:
Your data is a dict, not a list, so slicing isn't available. (There's also the philosophical issue of whether you can assume that variable_id is the first item: Python dicts are ordered by insertion, but JSON objects are not.)
The simplest thing to do would be to simply remove the key you don't want.
with open("people_data.json") as f:
data = json.load(f)
people = dict(data)
people.pop("variable_id")
# Or just data.pop("variable_id") if you don't care about preserving the original dict.
CodePudding user response:
That is a structure data misleading. In python exist many structures built-in in the language like list, tuple, dict and json and you are using the method of access one structure into another.
A list is acessed by a positional index starting at 0 (zero), for example:
l = [1,2,3]
l[0] # 1
l[2] # 2
In a dict we use the key to get the value:
d = {'key':'value','key2':'value2'}
d['key'] # 'value'
d['key2'] # 'value2'
So in your example you can use:
f = open("people_data.json", "r")
data = json.load(f)
people['skills'] # print a list of dicts
# [
# {
# "area": "programmer",
# "level": "junior",
# "comments": "..."
# }
# ]
And if you don't know the keys from the dict you can iterate over them:
keys = d.keys()
d[keys[0]] # for the first result returned by the keys() method
Reference: data structures
