Running Python 3.6 without supporting additional modules. I would like to append/add new entries to the "polygon" section. Any suggestions how:
JSON Structure:
{
"messageId":775,
"value":{
"dataFrames":[
{
"content":{
"workZone":[
{
"item":{
"text":"Test"
}
},
{
"item":{
"itis":333
}
}
]
},
"duratonTime":24,
"frameType":"road Signage",
"msgId":{
"roadSignID":{
"mutcdCode":"warning",
"position":{
"elevation":634.0,
"lat":30.2,
"long":-80.5
},
"viewAngle":"111111"
}
},
"priority":1,
"regions":[
{
"anchor":{
"elevation":634.0,
"lat":34.3,
"long":-80.5
},
"description":{
"geometry":{
"direction":"0000",
"laneWidth":5.123,
"polygon":[
[
]
]
}
},
"directionality":"forward"
}
],
"sspLocationRights":1,
"sspMsgRights1":0,
"sspMsgRights2":0,
"sspTimRights":1,
"startTime":1599041581.5259035,
"startYear":2020
}
],
"msgCnt":0,
"packetID":775,
"source":"XX"
}
}
I tried to form a JSON and adding a String for the polygon but it is being added with quotes. So not sure if the best way is to access the polygon section and add new entries.
Expected JSON:
{
"messageId":775,
"value":{
"msgCnt":0,
"packetID":775,
"source":"C-V2X",
"dataFrames":[
{
"sspTimRights":1,
"frameType":"road Signage",
"msgId":{
"roadSignID":{
"position":{
"lat":-80.38466909433639,
"long":37.17942971412366,
"elevation":634.0
},
"viewAngle":"1000000000000000",
"mutcdCode":"warning"
}
},
"startYear":2020,
"startTime":1598992048.1489706,
"duratonTime":24,
"priority":1,
"sspLocationRights":1,
"regions":[
{
"anchor":{
"lat":-80.38466909433639,
"long":37.17942971412366,
"elevation":634.0
},
"directionality":"forward",
"description":{
"geometry":{
"direction":"1000000000000000",
"laneWidth":5.123,
"polygon":[
[
[
37.17942971412366,
-80.38466909433639
],
[
37.179543821887314,
-80.38487318094833
],
[
37.17967679727881,
-80.38510713731363
],
[
37.17995588265411,
-80.38560355518067
],
[
37.17998272884397,
-80.38557977915941
],
[
37.179703594552834,
-80.38508327461031
],
[
37.17957064376986,
-80.38484936187977
],
[
37.17945660930624,
-80.38464540586482
],
[
37.17942971412366,
-80.38466909433639
]
]
]
}
}
}
],
"sspMsgRights1":0,
"sspMsgRights2":0,
"content":{
"workZone":[
{
"item":{
"text":"Buffer Area"
}
},
{
"item":{
"itis":775
}
}
]
}
}
]
}
}
As #Gledi suggested. Doing a List is the proper way to insert the "polygon" information into the JSON structure.
Assuming data points to the dict in the question - the code below should work.
data['value']['dataFrames'][0]['regions'][0]['description']['geometry']['polygon'][0].append('something')
Related
As title suggests, I have this document structure:
{
"_id":ObjectId("61e53553ac31665894ebf6bc"),
"questionID":"8",
"questionContent":"find it",
"questoinAnswer":"it's here",
"questionStatus":"active",
"questionImage":"some image",
"hints":[
{
"hintID":"1",
"hintSubject":"in you pucket",
"hintContent":"bla bla bla",
"hintType":"private",
"hintStatus":"Active",
"time":"2022-01-23 11:02:41.976391"
},
{
"hintID":"2",
"hintSubject":"red sea",
"hintContent":"bla bla bla",
"hintMedia":"some media",
"hintType":"puplic",
"hintStatus":"Active",
"time":"2022-01-23 11:05:47.567226"
}
]
}
I want to retrieve only the values of hintSubject if the hintType is free and hintStatus is active and put it into a list
Use the below aggregation query where list of hintSubject is stored in hintSubject key in root dictionary key.
from pymongo import MongoClient
c = MongoClient()
db = c["db_name"]
col = db["sample_collection"]
for x in col.aggregate([
{
"$addFields": {
"hintSubject": {
"$reduce": {
"input": "$hints",
"initialValue": [],
"in": {
"$concatArrays": [
"$$value",
{
"$cond": {
"if": {
"$and": [
{
"$eq": [
"$$this.hintType",
"free"
]
},
{
"$eq": [
"$$this.hintStatus",
"Active"
]
},
]
},
"then": [
"$$this.hintSubject"
],
"else": [],
},
},
],
},
},
}
}
}
])
print(x["hintSubject"])
Mongo Playground Sample Execution
I'm trying the parse the following JSON data without storing it in a file, using Python.
{
"select": {
"value": "s_name"
},
"from": "student",
"where": {
"in": [
"s_id",
{
"select": {
"value": "s_id"
},
"from": "student_course",
"where": {
"in": [
"c_id",
{
"select": {
"value": "c_id"
},
"from": "course",
"where": {
"or": [
{
"and": [
{
"eq": [
"c_name",
{
"literal": "DSA"
}
]
},
{
"eq": [
"c_name",
{
"literal": "dbms"
}
]
}
]
},
{
"eq": [
"c_name",
{
"literal": "algorithm"
}
]
}
]
}
}
]
}
}
]
}
}
I'm using the following code:
import json
x = "JSON Data which is shared above"
y = json.dumps(x)
jsonDict = json.loads(y)
print (jsonDict['where'])
And not sure, how to proceed further, could you please advise, how it can be done?
I want to fetch the value of all objects, especially where clause.
json.dumps() takes an object and encodes it into a JSON string. But you are trying to take a JSON string and decode it into an object (a dict in this case). The method you should be applying against x therefore is json.loads(). You can then convert the resulting dict back into a JSON string, y, with json.dumps():
import json
x = """{
"select": {
"value": "s_name"
},
"from": "student",
"where": {
"in": [
"s_id",
{
"select": {
"value": "s_id"
},
"from": "student_course",
"where": {
"in": [
"c_id",
{
"select": {
"value": "c_id"
},
"from": "course",
"where": {
"or": [
{
"and": [
{
"eq": [
"c_name",
{
"literal": "DSA"
}
]
},
{
"eq": [
"c_name",
{
"literal": "dbms"
}
]
}
]
},
{
"eq": [
"c_name",
{
"literal": "algorithm"
}
]
}
]
}
}
]
}
}
]
}
}"""
jsonDict = json.loads(x) # from string to a dict
print(jsonDict['where'])
y = json.dumps(jsonDict) # from dict back to a string
Prints:
{'in': ['s_id', {'select': {'value': 's_id'}, 'from': 'student_course', 'where': {'in': ['c_id', {'select': {'value': 'c_id'}, 'from': 'course', 'where': {'or': [{'and': [{'eq': ['c_name', {'literal': 'DSA'}]}, {'eq': ['c_name', {'literal': 'dbms'}]}]}, {'eq': ['c_name', {'literal': 'algorithm'}]}]}}]}}]}
I'm trying to use the Spotify's API to get from a playlist all the track's id
I think that I just don't really know how to use json on Python as it's my first time using API's
This is the json that I get when requesting for a random playlist:
{
"items":[
{
"added_at":"2020-02-20T19:08:11Z",
"added_by":{
},
"is_local":False,
"primary_color":"None",
"track":{
"album":{
"album_type":"single",
"artists":[
{
"external_urls":{
"spotify":"https://open.spotify.com/artist/1k5UEOU4igPC0NoHjEekha"
},
"href":"https://api.spotify.com/v1/artists/1k5UEOU4igPC0NoHjEekha",
"id":"1k5UEOU4igPC0NoHjEekha",
"name":"Milkoi",
"type":"artist",
"uri":"spotify:artist:1k5UEOU4igPC0NoHjEekha"
},
{
"external_urls":{
"spotify":"https://open.spotify.com/artist/3U2oWd07HPgl60o8RBMG4P"
},
"href":"https://api.spotify.com/v1/artists/3U2oWd07HPgl60o8RBMG4P",
"id":"3U2oWd07HPgl60o8RBMG4P",
"name":"Miraie",
"type":"artist",
"uri":"spotify:artist:3U2oWd07HPgl60o8RBMG4P"
}
],
"available_markets":[ ],
"external_urls":{
"spotify":"https://open.spotify.com/album/69Y9i1D5TyQGxWdqFNRIhC"
},
"href":"https://api.spotify.com/v1/albums/69Y9i1D5TyQGxWdqFNRIhC",
"id":"69Y9i1D5TyQGxWdqFNRIhC",
"images":[
{
"height":640,
"url":"https://i.scdn.co/image/4ea41b9dde13c6cb31fff8fe3c5ee90076370885",
"width":640
},
{
"height":300,
"url":"https://i.scdn.co/image/6edf03567c0379d246c750147fd31a74574e4e27",
"width":300
},
{
"height":64,
"url":"https://i.scdn.co/image/fbbc5cca3adbaf433f43917012939c3e2c35c5eb",
"width":64
}
],
"name":"ミユキ",
"release_date":"2018-09-30",
"release_date_precision":"day",
"total_tracks":1,
"type":"album",
"uri":"spotify:album:69Y9i1D5TyQGxWdqFNRIhC"
},
"artists":[
{
"external_urls":{
"spotify":"https://open.spotify.com/artist/1k5UEOU4igPC0NoHjEekha"
},
"href":"https://api.spotify.com/v1/artists/1k5UEOU4igPC0NoHjEekha",
"id":"1k5UEOU4igPC0NoHjEekha",
"name":"Milkoi",
"type":"artist",
"uri":"spotify:artist:1k5UEOU4igPC0NoHjEekha"
},
{
"external_urls":{
"spotify":"https://open.spotify.com/artist/3U2oWd07HPgl60o8RBMG4P"
},
"href":"https://api.spotify.com/v1/artists/3U2oWd07HPgl60o8RBMG4P",
"id":"3U2oWd07HPgl60o8RBMG4P",
"name":"Miraie",
"type":"artist",
"uri":"spotify:artist:3U2oWd07HPgl60o8RBMG4P"
}
],
"available_markets":[ ],
"disc_number":1,
"duration_ms":211090,
"episode":False,
"explicit":False,
"external_ids":{
"isrc":"QM42K1817396"
},
"external_urls":{
"spotify":"https://open.spotify.com/track/77xwKl9jpVLO6VmNlwGwtm"
},
"href":"https://api.spotify.com/v1/tracks/77xwKl9jpVLO6VmNlwGwtm",
"id":"77xwKl9jpVLO6VmNlwGwtm",
"is_local":False,
"name":"ミユキ",
"popularity":43,
"preview_url":"https://p.scdn.co/mp3-preview/45e0b6cf4f358f5fbf6bebc1f019e67a780fa3f8?cid=2cd60e0da58b47518a61cec560d21ccd",
"track":True,
"track_number":1,
"type":"track",
"uri":"spotify:track:77xwKl9jpVLO6VmNlwGwtm"
},
"video_thumbnail":{
"url":"None"
}
},
{
"added_at":"2020-02-20T19:08:21Z",
"added_by":{
},
"href":"https://api.spotify.com/v1/users/akqpr9b7ycor7uw08afmc3hx4",
"id":"akqpr9b7ycor7uw08afmc3hx4",
"type":"user",
"uri":"spotify:user:akqpr9b7ycor7uw08afmc3hx4"
},
"is_local":False,
"primary_color":"None",
"track":{
"album":{
"album_type":"album",
"artists":[
{
"external_urls":{
"spotify":"https://open.spotify.com/artist/24HASvYQG1OvEFRWVWmOfx"
},
"href":"https://api.spotify.com/v1/artists/24HASvYQG1OvEFRWVWmOfx",
"id":"24HASvYQG1OvEFRWVWmOfx",
"name":"Kano",
"type":"artist",
"uri":"spotify:artist:24HASvYQG1OvEFRWVWmOfx"
}
],
"available_markets":[ ],
"external_urls":{
"spotify":"https://open.spotify.com/album/72sG7hFVmyFlxg9e7PfV0K"
},
"href":"https://api.spotify.com/v1/albums/72sG7hFVmyFlxg9e7PfV0K",
"id":"72sG7hFVmyFlxg9e7PfV0K",
"images":[
{
"height":640,
"url":"https://i.scdn.co/image/ab67616d0000b27327dfa5f6ab057a4ec5c53235",
"width":640
},
{
"height":300,
"url":"https://i.scdn.co/image/ab67616d00001e0227dfa5f6ab057a4ec5c53235",
"width":300
},
{
"height":64,
"url":"https://i.scdn.co/image/ab67616d0000485127dfa5f6ab057a4ec5c53235",
"width":64
}
],
"name":"rye",
"release_date":"2018-12-19",
"release_date_precision":"day",
"total_tracks":14,
"type":"album",
"uri":"spotify:album:72sG7hFVmyFlxg9e7PfV0K"
},
"artists":[
{
"external_urls":{
"spotify":"https://open.spotify.com/artist/24HASvYQG1OvEFRWVWmOfx"
},
"href":"https://api.spotify.com/v1/artists/24HASvYQG1OvEFRWVWmOfx",
"id":"24HASvYQG1OvEFRWVWmOfx",
"name":"Kano",
"type":"artist",
"uri":"spotify:artist:24HASvYQG1OvEFRWVWmOfx"
}
],
"available_markets":[ ],
"disc_number":2,
"duration_ms":222249,
"episode":False,
"explicit":False,
"external_ids":{
"isrc":"JPTE01809900"
},
"external_urls":{
"spotify":"https://open.spotify.com/track/6c9llTTjTcLgoHbKaJVw4f"
},
"href":"https://api.spotify.com/v1/tracks/6c9llTTjTcLgoHbKaJVw4f",
"id":"6c9llTTjTcLgoHbKaJVw4f",
"is_local":False,
"name":"六兆年と一夜物語",
"popularity":39,
"preview_url":"https://p.scdn.co/mp3-preview/3421753cafdf34dc1e34bba479f048ebd613f39f?cid=2cd60e0da58b47518a61cec560d21ccd",
"track":True,
"track_number":3,
"type":"track",
"uri":"spotify:track:6c9llTTjTcLgoHbKaJVw4f"
},
"video_thumbnail":{
"url":"None"
},
],
"limit":100,
"next":"None",
"offset":0,
"previous":"None",
"total":11
}
The ID is located at "items" -> "track" -> "id" for each track
I'm trying to get track's id but from all the tracks of the playlist so I can put them in a list.
If someone could help me it would be cool
Thanks in advance
I'm using Python 3
What I would do is put the response string into a response dictionary like so (if you haven't already)
resp_dict = json.load(your_response_string)
Then you could loop through and append all the track ids to a new list
newList = []
for x in response_dict['items']:
newList.append(x['track']['id'])
# To see if it worked
for item in newList:
print(item)
Let me know if that makes sense or you need some further explanation :)
I think my questions below different and im not able to find problem similar like mine...
I have json file (scanner.json) content values of nodes and links below
{
"nodes": [
"node1",
"node2",
"node3",
"node4",
"node5",
"node6",
"node7"
],
"links": [
[
"node1",
"node2",
"120"
],
[
"node1",
"node3",
"120"
],
[
"node1",
"node4",
"120"
],
[
"node2",
"node3",
"120"
],
[
"node2",
"node7",
"120"
]
]
}
I need to pass the values of nodes and links to NBI API below
Request URL: http://172.18.10.10:6233/cv/api/scanner
Body:
{
"channel": "scanner",
"action": "create_device",
"table": "U2",
"nodes::[
{
"node_hostname": "node1",
{,
{
"node_hostname": "node2",
},
{
"node_hostname": "node3"
}
"links": [
{
"source_hostname": "node1",
"dest_hostname": "node2",
"matric": "120",
},
]
}
How can I do that? parse and send via http url the content of the json file above to NBI API above.
Please assist and advise me. Thank you
Each key has a list of strings in them that I use to compare to another list. The dictionary is very nested so I use a recursive function to get the data of each key.
But it takes a long time to get through the entire list. Is there a faster way?
This is the code:
def get_industry(industry_data, industry_category): category_list = list()
for category in industry_category:
for key, item in category.items():
r = re.compile('|'.join([r'\b%s\b' % porter.stem("".join(w.split())) for w in item['key_list']]), flags=re.I)
words_found = r.findall(industry_data)
if words_found:
category_list.extend([key])
new_list = get_industry(' '.join(words_found), item["Subcategories"])
category_list.extend(new_list)
return category_list
This is an example of a JSON file.
[
{
"Agriculture": {
"Subcategories": [
{
"Fruits ": {
"Subcategories": [
{
"Fresh Fruits": {
"Subcategories": [
{
"Apricots": {
"Subcategories": [],
"key_list": [
"Apricots"
]
}
},
{
"Tamarinds": {
"Subcategories": [],
"key_list": [
"Tamarinds"
]
}
}
],
"key_list": [
"loganberries",
"medlars"
]
}
}
],
"key_list": [
"lemons",
"tangelos"
]
}
},
{
"Vegetables ": {
"Subcategories": [
{
"Beetroot": {
"Subcategories": [],
"key_list": [
"Beetroot"
]
}
},
{
"Wasabi": {
"Subcategories": [],
"key_list": [
"Wasabi"
]
}
}
],
"key_list": [
"kohlrabies",
"wasabi "
]
}
}
],
"key_list": [
"wasabi",
"batatas"
]
}
}
]
This is an example of a list I want it compared with.
["lemons","wasabi","washroom","machine","grapefruit","about","city"]
The answer should return this list:
["Agriculture","Vegetables","Wasabi"]
In order to compare list to list and return category, it takes about 3-5 seconds to finish the operation. I heard that using Pandas will significantly increase the speed.