Django combine two json objects to form a new array - json

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.

Related

Semantic segmentation labeling

I'm trynna make a scratch code of Semantic segmentation through U-Net. I'll use Cityscapes Dataset. I'm trying to make a dictionary(python) composed of the key(car, train, human, etc) and the value(rgb info). How can I match the dictionary with my ground_truth data?
example of labeling dictionary is like below
color_map = {
'0': [0, 0, 0], # unlabelled
'1': [128, 64, 128], # road
'2': [244, 35, 232], # sidewalk
'3': [70, 70, 70], # building
'4': [102, 102, 156], # wall
'5': [190, 153, 153], # fence
'6': [153, 153, 153], # pole
'7': [250,170, 30], # traffic_light
'8': [220, 220, 0], # traffic_sign
'9': [107, 142, 35], # vegetation
'10': [152, 251, 152], # terrain
'11': [0, 130, 180], # sky
'12': [220, 20, 60], # person
'13': [255, 0, 0], # rider
'14': [0, 0, 142], # car
'15': [0, 0, 70], # truck
'16': [0, 60, 100], # bus
'17': [0, 80, 100], # train
'18': [0, 0, 230], # motorcycle
'19': [119, 11, 32] # bicycle
}

How to create chart using Springboot Json api

i have this service that give back this Json result :
{
"MANNOUBA": 1,
"Medinine": 4,
"Gabes": 5,
"Tunis": 22,
"Beja": 3,
"Kebili": 0,
"Sfax": 11,
"Laundry Making": 6,
"italia": 0,
"Sousse": 6,
"Desk": 1,
"Jendouba": 3,
"Mahdia": 6,
"Ben Arous": 19,
"Zaghouan": 4,
"Gafsa": 0,
"Kairouan": 6,
"Monastir": 18,
"metos": 1,
"Eleonetech": 2,
"Nabeul": 22,
"Mannouba": 9,
"BENAROUS": 8,
"Ariana": 21,
"Bizerte": 3
}
i want to put this data in a Barchart For my angular Project with the names in the X axis and the Numbers in the Y axis
With using Highcharts, you can preprocess your data to the: [name, y] format and use category axis type. Example:
for (let key in data) {
chartData.push([key, data[key]]);
}
Highcharts.chart('container', {
xAxis: {
type: 'category'
},
series: [{
type: 'column',
data: chartData
}]
});
Live demo: http://jsfiddle.net/BlackLabel/cjk3uboh/
Highcharts angular wrapper: https://www.npmjs.com/package/highcharts-angular

Strange JSON keyerror python 3

I have been getting some strange key errors when trying to load a value after a few game ticks in my case, there is no modification going on cause most of it gets loaded from class internally at initiation, here is an quick example of the error im getting when trying to access.
also link to source is here, im pretty new and just have been coding for aint to long so please no judgement.
{'calleas': {'player': {'x': 5, 'y': 5, 'id': 'npc_1'}, '1': {'x': 6, 'y': 8, 'id': 'npc_2'}, '2': {'x': 5, 'y': 8, 'id': 'npc_3'}}, 'calleas_forest': {'player': {'x': 55, 'y': 5, 'id': 'npc_1'}}}
{'calleas': {'0': {'object_id': 7, 'x': 0, 'y': 5, 'walkable': True, 'gamestate': 'callaes_forest'}, '1': {'object_id': 7, 'x': 0, 'y': 4, 'walkable': True, 'gamestate': 'callaes_forest'}}, 'callaes_forest': {'0': {'object_id': 7, 'x': 56, 'y': 5, 'walkable': True, 'gamestate': 'callaes_forest'}, '1': {'object_id': 7, 'x': 56, 'y': 4, 'walkable': True, 'gamestate': 'callaes_forest'}}}
None
Traceback (most recent call last):
File "C:/Users/Jannick/PycharmProjects/NewRemake/Game.py", line 39, in <module>
g.start_game()
File "C:/Users/Jannick/PycharmProjects/NewRemake/Game.py", line 33, in start_game
self.update()
File "C:\Users\Jannick\PycharmProjects\NewRemake\GameHandler.py", line 106, in update
self.entity_handler.update()
File "C:\Users\Jannick\PycharmProjects\NewRemake\Entity\EntityHandler.py", line 21, in update
self.game.player.update()
File "C:\Users\Jannick\PycharmProjects\NewRemake\Entity\Entity.py", line 35, in update
self.move(x=1)
File "C:\Users\Jannick\PycharmProjects\NewRemake\Entity\Player.py", line 47, in move
self.game.map_handler.load(self.game.map_handler.new_map_name(dest_x, dest_y))
File "C:\Users\Jannick\PycharmProjects\NewRemake\World\MapBuilder.py", line 26, in load
self.get_map_configuration(map_config)
File "C:\Users\Jannick\PycharmProjects\NewRemake\World\MapBuilder.py", line 46, in get_map_configuration
"entitys": self.all_map_entitys[map_config]
KeyError: 'callaes_forest'
{'calleas': {'player': {'x': 5, 'y': 5, 'id': 'npc_1'}, '1': {'x': 6, 'y': 8, 'id': 'npc_2'}, '2': {'x': 5, 'y': 8, 'id': 'npc_3'}}, 'calleas_forest': {'player': {'x': 55, 'y': 5, 'id': 'npc_1'}}}

Convert Nested JSON to Pandas Column

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.

Use Node.js data in HTML with HAPI

I have a server.js page and it get datas from database. I want to use this datas in a HTML page. How can I get this datas.
I don't use Express but Hapi (because i'm happy lol).
This is my code :
<script>var ctx = document.getElementById('graph').getContext('2d');
var graph = new Chart(ctx, {
type: 'line',
data: {
labels: ['Lundi', 'Mardi', 'Mercredi', 'Jeudi', 'Vendredi', 'Samedi', 'Dimanche'],
datasets: [{
label: 'CPU',
data: [22, 19, 25, 65, 30, 47, 14],
backgroundColor: "rgba(153,255,51,0.4)"
}, {
label: 'RAM',
data: [31, 29, 31, 35, 28, 34, 30],
backgroundColor: "rgba(255,153,0,0.4)"
}]
}
});
</script>
I want to change "22, 19, 25, 65, 30, 47, 14" by the new values gets with postgreSQL.
Thanks for your help.