Convert Nested JSON to Pandas Column - json

I have a Json file as below:
[{
'instrument_token': 12335618, 'last_price': 31584.6,
'ohlc': {'open': 31080.1, 'high': 31590.0, 'low': 31049.05, 'close': 31114.7},
'depth': {'buy': [{'quantity': 40, 'price': 31576.4, 'orders': 1}, {'quantity': 160, 'price': 31576.0, 'orders': 1}], 'sell': [{'quantity': 200, 'price': 31584.6, 'orders': 2}, {'quantity': 60, 'price': 31584.65, 'orders': 1}]}
}]
I have tried as below:
df = json_normalize(ticks)
print(df)
This gives me a result as:
instrument_token last_price ohlc.open ohlc.high ohlc.low ohlc.close depth.buy depth.sell
0 12335618 31584.6 31080.1 31590.0 31049.05 31114.7 [{'quantity': 40, 'price': 31576.4, 'orders': ... [{'quantity': 200, 'price': 31584.6, 'orders':...
I want to further normalize the data of depth.buy & depth.sell columns in separate columns with column name as:
depth.buy.quantity1, depth.buy.price1, depth.buy.orders1,
depth.buy.quantity2, depth.buy.price2, depth.buy.orders2,
depth.sell.quantity1, depth.sell.price1, depth.sell.orders1,
depth.sell.quantity2, depth.sell.price2, depth.sell.orders2,
Is it possible to normalise further?

for this example dataset,you can do it like this.
from pandas.io.json import json_normalize
data = [{
'instrument_token': 12335618, 'last_price': 31584.6,
'ohlc': {'open': 31080.1, 'high': 31590.0, 'low': 31049.05, 'close': 31114.7},
'depth': {'buy': [{'quantity': 40, 'price': 31576.4, 'orders': 1},
{'quantity': 160, 'price': 31576.0, 'orders': 1}],
'sell': [{'quantity': 200, 'price': 31584.6, 'orders': 2},
{'quantity': 60, 'price': 31584.65, 'orders': 1}]
}
}]
df = json_normalize(data)
cols = ["depth.buy","depth.sell"]
for c in cols:
postdf = pd.DataFrame()
tmp = df[c].values
for i,val in enumerate(tmp):
vals = list(val.values())
keys = [f"{c}.{k}{i+1}"for k in val.keys()]
tmpdf =pd.DataFrame([vals],columns=keys)
postdf = pd.concat([postdf,tmpdf],axis=1)
df = pd.concat([df,postdf],axis=1)
df = df.drop(columns=[c])
note that,
tmp = df[c].values take the 0th element of the list.if you have multiple elements you have to loop over the elements.i assumed that all data inside one list.
if you need to get column names list (["depth.buy","depth.sell"]) dynamically,you can do it by checking dtypes of the df and get object type column names.

Related

How can I get all of x values from what I think is JSON

Python version: 3.10
Running a function returns this:
[{'type': 1, 'components': [{'type': 2, 'style': 1, 'label': 'She/Her', 'custom_id': 'She/Her'}, {'style': 1, 'label': 'He/Him', 'custom_id': 'He/Him', 'type': 2}]}]
How can I get all values of 'custom_id' within what is returned? Thank you!
You can do it like so:
myList = [{'type': 1, 'components': [{'type': 2, 'style': 1, 'label': 'She/Her', 'custom_id': 'She/Her'}, {'style': 1, 'label': 'He/Him', 'custom_id': 'He/Him', 'type': 2}]}]
for user in list(myList[0]["components"]):
print(user["custom_id"])
You can format your json here
https://jsonformatter.curiousconcept.com/
to see, wich list is in wich :)
#infinity wrote it similar.
[
{
"type":1,
"components":[
{
"type":2,
"style":1,
"label":"She/Her",
"custom_id":"She/Her"
},
{
"style":1,
"label":"He/Him",
"custom_id":"He/Him",
"type":2
}
]
}
]
myList = [{'type': 1, 'components': [{'type': 2, 'style': 1, 'label': 'She/Her', 'custom_id': 'She/Her'}, {'style': 1, 'label': 'He/Him', 'custom_id': 'He/Him', 'type': 2}]}]
for user in myList[0]['components']:
print(user['custom_id'])

Json decode error while importing from a csv file

I am writing a python program that load a json string and decode from a .csv file. The .csv file includs the title and one entry below for reference.
key,labels,raw_tweet
2017_Q3_270,"[0, 0]","{'in_reply_to_screen_name': None, 'user': {'profile_banner_url': 'https://pbs.twimg.com/profile_banners/148491006/1494299074', 'follow_request_sent': None, 'name': 'Vanessa', 'verified': False, 'profile_sidebar_fill_color': 'FFFFFF', 'profile_background_color': '352726', 'is_translator': False, 'profile_background_image_url_https': 'https://pbs.twimg.com/profile_background_images/578700342637895680/j-o_FCwY.png', 'id': 148491006, 'geo_enabled': True, 'profile_background_image_url': 'http://pbs.twimg.com/profile_background_images/578700342637895680/j-o_FCwY.png', 'default_profile': False, 'contributors_enabled': False, 'default_profile_image': False, 'location': 'everywhere', 'profile_background_tile': True, 'notifications': None, 'listed_count': 9, 'profile_link_color': '7FDBB6', 'protected': False, 'profile_image_url': 'http://pbs.twimg.com/profile_images/891824958225215488/h__HMMlC_normal.jpg', 'profile_image_url_https': 'https://pbs.twimg.com/profile_images/891824958225215488/h__HMMlC_normal.jpg', 'following': None, 'time_zone': 'Eastern Time (US & Canada)', 'friends_count': 588, 'url': 'https://Instagram.com/vmanks/', 'profile_text_color': '333333', 'followers_count': 541, 'utc_offset': -14400, 'id_str': '148491006', 'description': 'from the bronx, studying at cornell, slowly but surely finding solace', 'created_at': 'Wed May 26 21:01:46 +0000 2010', 'screen_name': 'vmankss', 'favourites_count': 19781, 'profile_use_background_image': True, 'profile_sidebar_border_color': 'FFFFFF', 'statuses_count': 50506, 'lang': 'en'}, 'retweet_count': 0, 'is_quote_status': False, 'in_reply_to_user_id': None, 'id': 901132409508421632, 'coordinates': None, 'entities': {'symbols': [], 'urls': [], 'user_mentions': [], 'hashtags': []}, 'text': ""I basically just go to financial aid to take candy from the candy bowl, y'all are unhelpful"", 'in_reply_to_status_id_str': None, 'in_reply_to_status_id': None, 'geo': None, 'favorited': False, 'place': {'country_code': 'US', 'bounding_box': {'type': 'Polygon', 'coordinates': [[[-76.547738, 42.41815], [-76.547738, 42.480827], [-76.469987, 42.480827], [-76.469987, 42.41815]]]}, 'attributes': {}, 'country': 'United States', 'url': 'https://api.twitter.com/1.1/geo/id/ae76bffcaf2bf545.json', 'full_name': 'Ithaca, NY', 'name': 'Ithaca', 'id': 'ae76bffcaf2bf545', 'place_type': 'city'}, 'favorite_count': 0, 'retweeted': False, 'timestamp_ms': '1503681683314', 'truncated': False, 'id_str': '901132409508421632', 'created_at': 'Fri Aug 25 17:21:23 +0000 2017', 'in_reply_to_user_id_str': None, 'contributors': None, 'source': 'Twitter for iPhone', 'lang': 'en', 'filter_level': 'low'}"
2015_Q1_494,"[0, 0]","{'in_reply_to_user_id_str': None, 'id_str': '577090329658175488', 'timestamp_ms': '1426424031067', 'in_reply_to_status_id_str': None, 'lang': 'en', 'favorited': False, 'retweeted': False, 'in_reply_to_status_id': None, 'id': 577090329658175488, 'filter_level': 'low', 'created_at': 'Sun Mar 15 12:53:51 +0000 2015', 'in_reply_to_user_id': None, 'place': {'country': 'United States', 'url': 'https://api.twitter.com/1.1/geo/id/a307591cd0413588.json', 'id': 'a307591cd0413588', 'country_code': 'US', 'place_type': 'city', 'attributes': {}, 'full_name': 'Buffalo, NY', 'bounding_box': {'type': 'Polygon', 'coordinates': [[[-78.912276, 42.826008], [-78.912276, 42.966451], [-78.79485, 42.966451], [-78.79485, 42.826008]]]}, 'name': 'Buffalo'}, 'truncated': False, 'entities': {'user_mentions': [], 'hashtags': [], 'symbols': [], 'trends': [], 'urls': []}, 'text': '""He licked coke off an encyclopedia"" only in south buffalo', 'retweet_count': 0, 'source': 'Twitter for iPhone', 'in_reply_to_screen_name': None, 'user': {'id_str': '480575646', 'friends_count': 367, 'profile_image_url': 'http://pbs.twimg.com/profile_images/571759767896629250/C-94okMM_normal.jpeg', 'profile_banner_url': 'https://pbs.twimg.com/profile_banners/480575646/1402863912', 'listed_count': 2, 'screen_name': 'MichaelaFeeney', 'lang': 'en', 'notifications': None, 'profile_text_color': '333333', 'verified': False, 'favourites_count': 3995, 'name': 'Michæla...', 'protected': False, 'statuses_count': 2666, 'id': 480575646, 'profile_sidebar_border_color': 'C0DEED', 'profile_use_background_image': True, 'profile_sidebar_fill_color': 'DDEEF6', 'is_translator': False, 'time_zone': None, 'profile_link_color': '0084B4', 'created_at': 'Wed Feb 01 17:11:27 +0000 2012', 'geo_enabled': True, 'url': None, 'contributors_enabled': False, 'following': None, 'default_profile_image': False, 'profile_background_image_url': 'http://abs.twimg.com/images/themes/theme1/bg.png', 'description': 'They call me Lông Isländ. Brockport2018✌', 'utc_offset': None, 'location': '', 'profile_image_url_https': 'https://pbs.twimg.com/profile_images/571759767896629250/C-94okMM_normal.jpeg', 'profile_background_image_url_https': 'https://abs.twimg.com/images/themes/theme1/bg.png', 'profile_background_tile': False, 'default_profile': True, 'followers_count': 221, 'follow_request_sent': None, 'profile_background_color': 'C0DEED'}, 'coordinates': {'type': 'Point', 'coordinates': [-78.805803, 42.869134]}, 'possibly_sensitive': False, 'geo': {'type': 'Point', 'coordinates': [42.869134, -78.805803]}, 'favorite_count': 0, 'contributors': None}"
2017_Q4_280,"[0, 0]","{'in_reply_to_screen_name': None, 'user': {'profile_banner_url': 'https://pbs.twimg.com/profile_banners/2812396208/1425183203', 'follow_request_sent': None, 'name': 'HunnyBon', 'verified': False, 'profile_sidebar_fill_color': '000000', 'profile_background_color': '000000', 'notifications': None, 'profile_background_image_url_https': 'https://abs.twimg.com/images/themes/theme1/bg.png', 'id': 2812396208, 'geo_enabled': True, 'profile_background_image_url': 'http://abs.twimg.com/images/themes/theme1/bg.png', 'default_profile': False, 'contributors_enabled': False, 'default_profile_image': False, 'location': 'New York, NY', 'profile_background_tile': False, 'translator_type': 'none', 'listed_count': 5, 'profile_link_color': '666666', 'protected': False, 'profile_image_url': 'http://pbs.twimg.com/profile_images/572570217272713216/rzw1Bbqs_normal.png', 'profile_image_url_https': 'https://pbs.twimg.com/profile_images/572570217272713216/rzw1Bbqs_normal.png', 'following': None, 'time_zone': None, 'friends_count': 68, 'url': 'http://www.hunnybon.com', 'profile_text_color': '000000', 'followers_count': 66, 'utc_offset': None, 'id_str': '2812396208', 'description': ""A Healthier Candy Store..organic, vegan, and nonGMO. Indulge your sweet tooth without the guilt. Chocolates, gummies, caramels...what's your indulgence?"", 'created_at': 'Tue Sep 16 03:56:36 +0000 2014', 'screen_name': 'HunnyBonSweets', 'favourites_count': 53, 'profile_use_background_image': False, 'profile_sidebar_border_color': '000000', 'lang': 'en', 'statuses_count': 252, 'is_translator': False}, 'retweet_count': 0, 'is_quote_status': False, 'in_reply_to_user_id': None, 'id': 925755798147313664, 'coordinates': {'type': 'Point', 'coordinates': [-74.0064, 40.7142]}, 'entities': {'symbols': [], 'urls': [{'expanded_url': '', 'display_url': 'instagram.com/p/Ba9WuoQlYuk/', 'url': '', 'indices': [98, 121]}], 'user_mentions': [], 'hashtags': []}, 'text': '🍫Hello November, and hello to our new Chocolate Matcha Truffles! 🍫RAW dark chocolate, CREAMY NUT… ', 'in_reply_to_status_id_str': None, 'in_reply_to_status_id': None, 'geo': {'type': 'Point', 'coordinates': [40.7142, -74.0064]}, 'favorited': False, 'reply_count': 0, 'place': {'country_code': 'US', 'bounding_box': {'type': 'Polygon', 'coordinates': [[[-74.026675, 40.683935], [-74.026675, 40.877483], [-73.910408, 40.877483], [-73.910408, 40.683935]]]}, 'attributes': {}, 'country': 'United States', 'url': '', 'full_name': 'Manhattan, NY', 'name': 'Manhattan', 'id': '01a9a39529b27f36', 'place_type': 'city'}, 'favorite_count': 0, 'retweeted': False, 'timestamp_ms': '1509552356646', 'possibly_sensitive': False, 'truncated': False, 'id_str': '925755798147313664', 'created_at': 'Wed Nov 01 16:05:56 +0000 2017', 'quote_count': 0, 'in_reply_to_user_id_str': None, 'contributors': None, 'source': '', 'lang': 'en', 'filter_level': 'low'}"
I am trying to load raw_tweet, which is a json object as a string and decode it into a json object. I keep getting errors regardless of how I decode the string.
import csv
import json
with open('testfile.csv','r', encoding='utf-8', newline='') as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
jobj = row['raw_tweet'].replace("\'", "\"")
jobj = jobj.replace("None", "\"\"")
json.loads(jobj)
How I load the csv file. When I run the program, I get the following error. I also trying using panda dataframe to load and decode it into json object. I failed. Please suggest where I did wrong.
Traceback (most recent call last):
File "/Sandbox/csvfile.py", line 9, in <module>
json.loads(jobj)
File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/json/__init__.py", line 357, in loads
return _default_decoder.decode(s)
File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/json/decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/json/decoder.py", line 355, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 184 (char 183)
So in your csv file within the column raw tweet there are instances of False without any quotes. Also replacing the single quotes to double quotes has major break condition like your json already has strings like y'all which inherently uses single quote. So we only need to replace quotes for the keys and actual values and not quotes that occur within the string. So there are a lot of conditions to be replaced.
So I would rather suggest a different way of evaluating the csv and dumping jsons of the raw_tweet column.
import pandas as pd
data = pd.read_csv("test.csv").to_dict('records')
for d in data:
raw_tweet_dict = eval(d['raw_tweet'])
with open("json_dump.json", "w") as fp:
json.dump(raw_tweet_dict, fp)
You can use the raw_tweet_dict as a dictionary if this needs further transformation.
Alternatively you can also use your approach but you have add a lot of condition which I have added for now, it should work on your csv sample.
with open("test.csv", "r") as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
jobj = row['raw_tweet'].replace('"', "'")
jobj = jobj.replace("None", "''")
jobj = jobj.replace("False", "'False'").replace("True", "'True'")
jobj = jobj.replace("':", '\":').replace(": '", ': \"').replace("',", '\",').replace(", '", ', \"').replace("{'", '{\"').replace("'}", '\"}')
json.loads(jobj)

Turning a multi-dictionary JSON into a Pandas dataframe

I would like to turn a JSON data structure into a pandas dataframe. My data is retrieved from OpenWeatherMap. The resulting JSON contain multiple nested dictionaries which contain weather data on cities, divided by the URL where the data are retrieved from. Here the last two lines of the JSON, called json_data:
http://api.openweathermap.org/data/2.5/weather?units=Imperial&APPID=a13759df887d2de294c2c7adef912758&q=new norfolk:
{'coord': {'lon': 147.0587, 'lat': -42.7826}, 'weather': [{'id': 803, 'main': 'Clouds', 'description': 'broken clouds', 'icon': '04d'}], 'base': 'stations', 'main': {'temp': 46.04, 'feels_like': 44.29, 'temp_min': 43.92, 'temp_max': 51.93, 'pressure': 1000, 'humidity': 74}, 'visibility': 10000, 'wind': {'speed': 4, 'deg': 319, 'gust': 15.99}, 'clouds': {'all': 77}, 'dt': 1652657623, 'sys': {'type': 2, 'id': 2031307, 'country': 'AU', 'sunrise': 1652649449, 'sunset': 1652684337}, 'timezone': 36000, 'id': 2155415, 'name': 'New Norfolk', 'cod': 200}
http://api.openweathermap.org/data/2.5/weather?units=Imperial&APPID=a13759df887d2de294c2c7adef912758&q=fortuna:
{'coord': {'lon': -124.1573, 'lat': 40.5982}, 'weather': [{'id': 801, 'main': 'Clouds', 'description': 'few clouds', 'icon': '02d'}], 'base': 'stations', 'main': {'temp': 66.67, 'feels_like': 66.18, 'temp_min': 64.98, 'temp_max': 67.93, 'pressure': 1017, 'humidity': 67}, 'visibility': 10000, 'wind': {'speed': 17.27, 'deg': 360}, 'clouds': {'all': 20}, 'dt': 1652657623, 'sys': {'type': 2, 'id': 2040243, 'country': 'US', 'sunrise': 1652619589, 'sunset': 1652671580}, 'timezone': -25200, 'id': 5563839, 'name': 'Fortuna', 'cod': 200}
However, when I turn the JSON into a Pandas Dataframe, only the last dictionary goes into the dataframe.
Here is my code:
pd.set_option('display.max_columns', None)
pd.json_normalize(json_data)
Here is the result (I cannot copy the panda dataframe directly without losing formatting).
Why is only the last dictionary turned into a dataframe? How can I get a multiple-line dataframe?
If you're only seeing one line in your dataframe, you are probably overwriting your json_data with the last value.
Besides, you can normalize the weather column separately and join it to the rest:
json_data = [
{'coord': {'lon': 147.0587, 'lat': -42.7826}, 'weather': [{'id': 803, 'main': 'Clouds', 'description': 'broken clouds', 'icon': '04d'}], 'base': 'stations', 'main': {'temp': 46.04, 'feels_like': 44.29, 'temp_min': 43.92, 'temp_max': 51.93, 'pressure': 1000, 'humidity': 74}, 'visibility': 10000, 'wind': {'speed': 4, 'deg': 319, 'gust': 15.99}, 'clouds': {'all': 77}, 'dt': 1652657623, 'sys': {'type': 2, 'id': 2031307, 'country': 'AU', 'sunrise': 1652649449, 'sunset': 1652684337}, 'timezone': 36000, 'id': 2155415, 'name': 'New Norfolk', 'cod': 200},
{'coord': {'lon': -124.1573, 'lat': 40.5982}, 'weather': [{'id': 801, 'main': 'Clouds', 'description': 'few clouds', 'icon': '02d'}], 'base': 'stations', 'main': {'temp': 66.67, 'feels_like': 66.18, 'temp_min': 64.98, 'temp_max': 67.93, 'pressure': 1017, 'humidity': 67}, 'visibility': 10000, 'wind': {'speed': 17.27, 'deg': 360}, 'clouds': {'all': 20}, 'dt': 1652657623, 'sys': {'type': 2, 'id': 2040243, 'country': 'US', 'sunrise': 1652619589, 'sunset': 1652671580}, 'timezone': -25200, 'id': 5563839, 'name': 'Fortuna', 'cod': 200}
]
pd.set_option('display.max_columns', None)
df = pd.json_normalize(json_data)
df = df.loc[:, df.columns!='weather'].join(pd.json_normalize(json_data, record_path='weather', record_prefix='weather.'))
print(df)
Output:
base visibility dt timezone id name cod \
0 stations 10000 1652657623 36000 2155415 New Norfolk 200
1 stations 10000 1652657623 -25200 5563839 Fortuna 200
coord.lon coord.lat main.temp main.feels_like main.temp_min \
0 147.0587 -42.7826 46.04 44.29 43.92
1 -124.1573 40.5982 66.67 66.18 64.98
main.temp_max main.pressure main.humidity wind.speed wind.deg \
0 51.93 1000 74 4.00 319
1 67.93 1017 67 17.27 360
wind.gust clouds.all sys.type sys.id sys.country sys.sunrise \
0 15.99 77 2 2031307 AU 1652649449
1 NaN 20 2 2040243 US 1652619589
sys.sunset weather.id weather.main weather.description weather.icon
0 1652684337 803 Clouds broken clouds 04d
1 1652671580 801 Clouds few clouds 02d
As you can see, both lines are in the dataframe

Django combine two json objects to form a new array

I have two json objects as follow
Id:1
{"points":[{"x":109,"y":286,"r":1,"color":"black"},{"x":108,"y":285,"r":1,"color":"black"},{"x":106,"y":282,"r":1,"color":"black"},{"x":103,"y":276,"r":1,"color":"black"},],"lines":[{"x1":109,"y1":286,"x2":108,"y2":285,"strokeWidth":"2","strokeColor":"black"},{"x1":108,"y1":285,"x2":106,"y2":282,"strokeWidth":"2","strokeColor":"black"},{"x1":106,"y1":282,"x2":103,"y2":276,"strokeWidth":"2","strokeColor":"black"}]}
Id-2
{"points":[{"x":524,"y":343,"r":1,"color":"black"},{"x":523,"y":342,"r":1,"color":"black"},{"x":521,"y":339,"r":1,"color":"black"},{"x":520,"y":334,"r":1,"color":"black"},{"x":514,"y":319,"r":1,"color":"black"}],"lines":[{"x1":524,"y1":343,"x2":523,"y2":342,"strokeWidth":"2","strokeColor":"black"},{"x1":523,"y1":342,"x2":521,"y2":339,"strokeWidth":"2","strokeColor":"black"},{"x1":521,"y1":339,"x2":520,"y2":334,"strokeWidth":"2","strokeColor":"black"},{"x1":520,"y1":334,"x2":514,"y2":319,"strokeWidth":"2","strokeColor":"black"}]}
I am trying to merge these two data onto a canvas
I am able to retrieve a single file but combining them i am not able to do
def loadDrawing(request):
""" Function to load the drawing with drawingID if it exists."""
try:
# Getting JSON object string of saved drawing.
drawingJSONData = Drawing.objects.get(id = 1).drawingJSONText
# drawingJSONData1 = Drawing.objects.get(id=1).drawingJSONText
# drawingJSONData2 = Drawing.objects.get(id=2).drawingJSONText
# Seding context with appropriate information
context = {
"loadIntoJavascript" : True,
"JSONData" : drawingJSONData
}
# Editing response headers and returning the same
response = modifiedResponseHeaders(render(request, 'MainCanvas/index.html', context))
return response
My model in django
class Drawing(models.Model):
drawingJSONText = models.TextField(null = True)
My .js file to load the drawing and parsing it from server to JSON object and pushing the loaded points into an array
// Checking if the drawing to be loaded exists
if (document.getElementById('JSONLoadData') != null)
{
// Parsing the loaded drawing from server to a JSON Object
var loadedData = JSON.parse(JSONLoadData.value)
// Iterating through all the points in the loaded drawing
for(let i = 0; i < loadedData['points'].length; i++)
{
// Saving the point and drawing the same in the svg canvas
const point = svg.append('circle')
.attr('cx', loadedData['points'][i]['x'])
.attr('cy', loadedData['points'][i]['y'])
.attr('r', loadedData['points'][i]['r'])
.style('fill', loadedData['points'][i]['color']);
// Pushing the point inside points array
points.push(point);
}
// Iterating through all the lines in the loaded drawing
for(let i = 0; i < loadedData['lines'].length; i++)
{
// Saving the line and drawing the same in the svg canvas
const line = svg.append('line')
.attr('x1', loadedData['lines'][i]['x1'])
.attr('y1', loadedData['lines'][i]['y1'])
.attr('x2', loadedData['lines'][i]['x2'])
.attr('y2', loadedData['lines'][i]['y2'])
.attr('stroke-width', loadedData['lines'][i]['strokeWidth'])
.style('stroke', loadedData['lines'][i]['strokeColor']);
// Pushing the line inside lines array
lines.push(line);
}
}
});
Edited :
If my model is as follows
class Drawing(models.Model):
drawingJSONText = models.TextField(null=True)
project = models.CharField(max_length=250)
How can i filter data based on project
Lets say i have three datasets
1st one contains project = a
2nd one contains project = b
3rd one contains project = a
4th one contains project = a
How can i add datapoints like above by filtering data Drawing.objects.filter(project=a)
then based on the queryset i have three data points and corresponding data are plotted on canvas as above
I'm not entirely sure this is what you want, but are you trying to combine id-1 and id-2? If I think I understand what you are trying to do, will using the + operator work for you in this case?
drawingJSONData1 = json.loads(Drawing.objects.get(id=1).drawingJSONText)
drawingJSONData2 = json.loads(Drawing.objects.get(id=1).drawingJSONText)
drawingJSONData = dict()
drawingJSONData["points"] = drawingJSONData1["points"]+drawingJSONData1["points"]
drawingJSONData["lines"] = drawingJSONData2["lines"]+drawingJSONData2["lines"]
With your example above, you'd end up with:
{'points': [{'x': 109, 'y': 286, 'r': 1, 'color': 'black'},
{'x': 108, 'y': 285, 'r': 1, 'color': 'black'},
{'x': 106, 'y': 282, 'r': 1, 'color': 'black'},
{'x': 103, 'y': 276, 'r': 1, 'color': 'black'},
{'x': 524, 'y': 343, 'r': 1, 'color': 'black'},
{'x': 523, 'y': 342, 'r': 1, 'color': 'black'},
{'x': 521, 'y': 339, 'r': 1, 'color': 'black'},
{'x': 520, 'y': 334, 'r': 1, 'color': 'black'},
{'x': 514, 'y': 319, 'r': 1, 'color': 'black'}],
'lines': [{'x1': 109,
'y1': 286,
'x2': 108,
'y2': 285,
'strokeWidth': '2',
'strokeColor': 'black'},
{'x1': 108,
'y1': 285,
'x2': 106,
'y2': 282,
'strokeWidth': '2',
'strokeColor': 'black'},
{'x1': 106,
'y1': 282,
'x2': 103,
'y2': 276,
'strokeWidth': '2',
'strokeColor': 'black'},
{'x1': 524,
'y1': 343,
'x2': 523,
'y2': 342,
'strokeWidth': '2',
'strokeColor': 'black'},
{'x1': 523,
'y1': 342,
'x2': 521,
'y2': 339,
'strokeWidth': '2',
'strokeColor': 'black'},
{'x1': 521,
'y1': 339,
'x2': 520,
'y2': 334,
'strokeWidth': '2',
'strokeColor': 'black'},
{'x1': 520,
'y1': 334,
'x2': 514,
'y2': 319,
'strokeWidth': '2',
'strokeColor': 'black'}]}
EDIT: added the gets wrapped in json.loads to convert string to Python object as I don't know what kind of field that is and given the error being seen.

Convert list of nested dictionary into dictionary in Python

I have a list of nested dictionary as below. There is list inside the dictionary as well. I don't want to change the inner list but to turn the entire list into dictionary. The list is as below:
[{"id" : "A", "data" : [{"key_1" : 012},{"key_2" : 123}, {"key_3" : 234}]}]
I only want to change the list itself to dictionary without changing the inner list as below:
{{"id" : "A", "data" : [{"key_1" : 012},{"key_2" : 123}, {"key_3" : 234}]}}
Appreciate your help in this.
Use a dictionary comprehension and zip the list of dictionaries up with whatever list of keys you want. Here is an example using a subset of ascii lowercase letters:
{ pair[0]: pair[1] for pair in list(zip([*string.ascii_lowercase[0:len(input)]], input))}
>>> foo = [ { 'Age': 32,
'Emp_id': 'A',
'Gender': 'M',
'Result': [ {'Incentive': 3000, 'Month': 'Aug'},
{'Incentive': 3500, 'Month': 'Sep'},
{'Incentive': 2000, 'Month': 'Oct'}]},
{ 'Age': 35,
'Emp_id': 'B',
'Gender': 'M',
'Result': [{'Incentive': 1500, 'Month': 'Aug'}]},
{ 'Age': 31,
'Emp_id': 'C',
'Gender': 'F',
'Result': [ {'Incentive': 5000, 'Month': 'Aug'},
{'Incentive': 2400, 'Month': 'Sep'}]}]
>>> { pair[0]: pair[1] for pair in list(zip([*string.ascii_lowercase[0:len(input)]], input))}
>>> { 'a': { 'Age': 32,
'Emp_id': 'A',
'Gender': 'M',
'Result': [ {'Incentive': 3000, 'Month': 'Aug'},
{'Incentive': 3500, 'Month': 'Sep'},
{'Incentive': 2000, 'Month': 'Oct'}]},
'b': { 'Age': 35,
'Emp_id': 'B',
'Gender': 'M',
'Result': [{'Incentive': 1500, 'Month': 'Aug'}]},
'c': { 'Age': 31,
'Emp_id': 'C',
'Gender': 'F',
'Result': [ {'Incentive': 5000, 'Month': 'Aug'},
{'Incentive': 2400, 'Month': 'Sep'}]}}
note: you can pretty print code as follows:
import pp = pprint.PrettyPrinter(indent=4)
pp.pprint(data)