I have a json file with this structure:
[
{
"_id": "62b2ebff955fe1001d225781",
"datasetName": "comments",
"action": "dataset",
"comment": "Initial data!",
"instances": [
"62b2eb94955fe1001d22576a",
"62b2eba1955fe1001d22576e",
"62b2eba9955fe1001d225770",
"62b2ebb9955fe1001d225772",
"62b2ebcc955fe1001d225774",
"62b2ebe2955fe1001d225778"
],
"label": [
"Contemporary",
"Tango"
]
}
]
I wanted to know how can I access the values of "label" and also how can I count the length of "instances" object.
So your json is a list of dict. You can load it with the json standard library. Then you can iterate over the elements in the list. As each of these elements is a dict item, you can then get the instances list by it's key. As it is a list, you can simple call the len() function to get the length.
See the code below as an example:
import json
with open("somefile.json") as infile:
data = json.load(infile)
for element in data:
print(len(element["instances"]))
Note that if your json file contains more elements in the root list, it will of course print out the length of the instances list for each of these elements.
Related
This code are successful to get the "version" and "shapes" data. (for i in data.get("shapes"):)
but when i swtch "shapes" to the "label" ,the problme come
TypeError: 'NoneType' object is not iterable
Thanks help.
{
"version": "4.5.7",
"flags": {},
"shapes": [
{
"label": "2",
"points": [
[
602.8,
590.2
],
[
610.3,
642.0
]
]
}
],
"imagePath": "ladybug_13451176_20200410_141545_ColorProcessed_000497_Cam0_20059_026-2678.png",
"imageWidth": 1024
}
import json
import jsonpath
import io
with open("B123.json", mode="r") as dict:
data = json.load(dict)
for i in data.get("shapes"):
print(i,end="")
data is of type dict. Calling dict.get() would either return the value (if present) or None (if not present).
So if your data varies and might have no defined "shapes", don't just iterate over it as you could be iterating on a None object. So replace this:
for i in data.get("shapes"):
Instead, put a check first.
if "shapes" in data:
for i in data.get("shapes"):
Or better yet maximize the or operation which continues to the next if the previous has a false value.
for i in data.get("shapes") or []:
Because "shape" is a list of dict, you cabiterate it. But label is inside shapes dict, you can't just replace "shapes" by "label", also when you will have obtained the contents of label, you still won't be able to iterate it because the value of key label is not a list or dict
I want to parse the value from json response using python and assign additional value to the list
{ "form": [{ "box": [60,120,260,115], "text": "hello", "label": "question", "words": [{ "box": [90,190,160,215 ],"text": "hello"} ], "linking": [[0,13]],"id": 0 }]}
I am trying to parse the value and assign to a variable using python. What I am trying to achieve is:
If the actual output is ([60,120,260,115],hello) I wanted to add few more values to the list: Thus expected output should be:
([60,120,260,120,260,115,60,115],hello)
try this:
tmp_json = { "form": [{ "box": [60,120,260,115], "text": "hello", "label": "question", "words": [{ "box": [90,190,160,215 ],"text": "hello"} ], "linking": [[0,13]],"id": 0 }]}
# Then do whatever you need to do with the list by accessing it as follows
# tmp_json["form"][0]["box"]
you can iterate through all elements of list here and if each item matches required condition extend the existing list with required values.
# Pseudocode
for item in data["form"]:
# check each item's box attribute has all such elements i.e 60,120,260,115
# AND item's text attribute has value "hello"
# If matches then to add extra values to box list you can use <list>.extend([115, 120 etc])
# e.g item["box"].extend([120, 115, 260])
I have a JSON file, and what I am trying to do is getting this specific field '_id'. Problem is that when I use json.load('input_file'), it says that my variable data is a list, not a dictionary, so I can't do something like:
for value in data['_id']:
print(data['_id'][i])
because I keep getting this error: TypeError: list indices must be integers or slices, not str
What I also tried to do is:
data = json.load(input_file)[0]
It kinda works. Now, my type is a dictionary, and I can access like this: data['_id']
But I only get the first '_id' from the archive...
So, what I would like to do is add all '_id' 's values into a list, to use later.
input_file = open('input_file.txt')
data = json.load(input_file)[0]
print(data['_id'])# only shows me the first '_id' value
Thanks for the help!
[{
"_id": "5436e3abbae478396759f0cf",
"name": "ISIC_0000000",
"updated": "2015-02-23T02:48:17.495000+00:00"
},
{
"_id": "5436e3acbae478396759f0d1",
"name": "ISIC_0000001",
"updated": "2015-02-23T02:48:27.455000+00:00"
},
{
"_id": "5436e3acbae478396759f0d3",
"name": "ISIC_0000002",
"updated": "2015-02-23T02:48:37.249000+00:00"
},
{
"_id": "5436e3acbae478396759f0d5",
"name": "ISIC_0000003",
"updated": "2015-02-23T02:48:46.021000+00:00"
}]
You want to print the _id of each element of your json list, so let's do it by simply iterating over the elements:
input_file = open('input_file.txt')
data = json.load(input_file) # get the data list
for element in data: # iterate on each element of the list
# element is a dict
id = element['_id'] # get the id
print(id) # print it
If you want to transform the list of elements into a list of ids for later use, you can use list comprehension:
ids = [ e['_id'] for e in data ] # get id from each element and create a list of them
As you can see the data is a list of dictionaries
for looping over data you need to use the following code
for each in data:
print each['_id']
print each['name']
print each['updated']
it says that my variable data is a list, not a dictionary, so I can't do something like:
for value in data['_id']:
print(data['_id'][i])
Yes, but you can loop over all the dictionaries in your list and get the values for their '_id' keys. This can be done in a single line using list comprehension:
data = json.load(input_file)
ids = [value['_id'] for value in data]
print(ids)
['5436e3abbae478396759f0cf', '5436e3acbae478396759f0d1', '5436e3acbae478396759f0d3', '5436e3acbae478396759f0d5']
Another way to achieve this is using the map built-in function of python:
ids = map(lambda value: value['_id'], data)
This creates a function that returns the value of the key _id from a dictionary using a lambda expression and then returns a list with the return value from this function applied on every item in data
My goal is to iterate through every element in classes and add the value of class in classes into a new list.
JSON Structure:
{
"images": [
{
"classifiers": [
{
"classes": [
{
"class": "street",
"score": 0.846
},
{
"class": "road",
"score": 0.85
}
]
}
]
}
]
}
In the above JSON example, the new list should contain:
{'street','road'}
I tried to iterate over json_data['images'][0]['classifiers']['classes'] and for each one list.append() the value of class.
list = list()
def func(json_data):
for item in json_data['images'][0]['classifiers']['classes']:
list.append(item['class'])
return(list)
I am receiving a TypeError which is:
TypeError: list indices must be integers or slices, not str
What I am getting from this TypeError is that it attempts to add a string to the list but list.append() does not accept a string as a paramet. I need to somehow convert the string into something else.
My question is what should I convert the string into so that list.append() will accept it as a parameter?
The first issue is that classifiers is also a list, so you need an additional index to get at classes. This will work:
for item in json_data['images'][0]['classifiers'][0]['classes']:
Second, you want the result as a set not a list, so you can do: return set(lst). Note that sets are unordered, so don't expect the ordering of items to match that of the list.
I want to save the information from a .json file as a dictionary containing other dictionaries. I attempted, but, when I try to access the first key, it is a string, rather than another dictionary. Here is my code:
with open('matches1.json', 'r') as json_file:
match_histories = json.load(json_file)
print(match_histories[key]['matches'])
for i in range(6):
print(match_histories[key][i])
The first print results in an error, the second results in 'matches'.
The file I want to load can be downloaded but the structure is basically:
{
"matches": [
{
"matchId": 1778839570,
"region": "NA",
"platformId": "NA1",
"matchMode": "CLASSIC",
"matchType": "MATCHED_GAME",
"matchCreation": 1427867835805,
"matchDuration": 3424,
"queueType": "RANKED_SOLO_5x5",
"mapId": 11,
"season": "SEASON2015",
"matchVersion": "5.6.0.194",
"participants": [
// more dictionaries
],
"participantIdentities": [
// more dictionaries
],
"teams": [
// more dictionaries
],
"timeline": {
"frames": [
// many frame dictionaries
],
"frameInterval": 60000
}
},
// more dictionaries
]
}
I saved it as matches1.json in the same directory as my code.
I have also tried putting
match_histories={}
before my other code, but that didn't help either.
How can I save this .json file as a dictionary containing dictionaries?
match_histories is a dictionary with one key, matches. The value is a list of dictionaries; loop over that list:
for match in match_histories['matches']:
print(match['matchId'])
Warning: the match objects are themselves large dictionaries.