How do I `jsonify` a list in Flask? [duplicate] - json

This question already has answers here:
Return JSON response from Flask view
(15 answers)
Closed 5 years ago.
Currently Flask would raise an error when jsonifying a list.
I know there could be security reasons https://github.com/mitsuhiko/flask/issues/170, but I still would like to have a way to return a JSON list like the following:
[
{'a': 1, 'b': 2},
{'a': 5, 'b': 10}
]
instead of
{ 'results': [
{'a': 1, 'b': 2},
{'a': 5, 'b': 10}
]}
on responding to a application/json request. How can I return a JSON list in Flask using Jsonify?

You can't but you can do it anyway like this. I needed this for jQuery-File-Upload
import json
# get this object
from flask import Response
#example data:
js = [ { "name" : filename, "size" : st.st_size ,
"url" : url_for('show', filename=filename)} ]
#then do this
return Response(json.dumps(js), mimetype='application/json')

jsonify prevents you from doing this in Flask 0.10 and lower for security reasons.
To do it anyway, just use json.dumps in the Python standard library.
http://docs.python.org/library/json.html#json.dumps

This is working for me. Which version of Flask are you using?
from flask import jsonify
...
#app.route('/test/json')
def test_json():
list = [
{'a': 1, 'b': 2},
{'a': 5, 'b': 10}
]
return jsonify(results = list)

Flask's jsonify() method now serializes top-level arrays as of this commit, available in Flask 0.11 onwards.
For convenience, you can either pass in a Python list: jsonify([1,2,3])
Or pass in a series of args: jsonify(1,2,3)
Both will be serialized to a JSON top-level array: [1,2,3]
Details here: https://flask.palletsprojects.com/en/2.2.x/api/?highlight=jsonify#flask.json.jsonify**

Solved, no fuss. You can be lazy and use jsonify, all you need to do is pass in items=[your list].
Take a look here for the solution
https://github.com/mitsuhiko/flask/issues/510

A list in a flask can be easily jsonify using jsonify like:
from flask import Flask,jsonify
app = Flask(__name__)
tasks = [
{
'id':1,
'task':'this is first task'
},
{
'id':2,
'task':'this is another task'
}
]
#app.route('/app-name/api/v0.1/tasks',methods=['GET'])
def get_tasks():
return jsonify({'tasks':tasks}) #will return the json
if(__name__ == '__main__'):
app.run(debug = True)

If you are searching literally the way to return a JSON list in flask and you are completly sure that your variable is a list then the easy way is (where bin is a list of 1's and 0's):
return jsonify({'ans':bin}), 201
Finally, in your client you will obtain something like
{ "ans": [ 0.0, 0.0, 1.0, 1.0, 0.0 ] }

josonify works... But if you intend to just pass an array without the 'results' key, you can use JSON library from python. The following conversion works for me.
import json
#app.route('/test/json')
def test_json():
mylist = [
{'a': 1, 'b': 2},
{'a': 5, 'b': 10}
]
return json.dumps(mylist)

Related

Django APIView data format from AJAX

I was trying to send an array of objects in views.py using APIView to insert multiple rows in 1 post request. This is my JavaScript data format:
const data = {
group_designation: [
{id: 1},
{id: 2},
{id: 3},
]
}
I run an insomnia app and it only accepts this kind of format:
{
"group_designation": [
{"id": 1},
{"id": 2},
]
}
However, if I send a post request using the javascript format stated above, it gives me a bad request error(400). This is the payload in network tab:
group_designation[0][id]: 1
group_designation[1][id]: 2
group_designation[2][id]: 3
In Django, this is the request.data result:
<QueryDict: {
'group_designation[0][id]': ['1'],
'group_designation[1][id]': ['2'],
'group_designation[2][id]': ['3']
}>
My code in Django:
def post(self, request):
temp_objects = []
new_data_format = {'group_designation': temp_objects}
serializer = GroupSerializer(data=new_data_format, many=True)
if serializer.is_valid(raise_exception=True):
group_data_saved = serializer.save()
return Response({
"success": "success!!!"
})
I was just trying to rewrite the data format so it will be saved but no luck trying. Please help. Thank you!

corrupted record from json file in pyspark due to False as entry

I have a json file that looks like this:
test= {'kpiData': [{'date': '2020-06-03 10:05',
'a': 'MINIMUMINTERVAL',
'b': 0.0,
'c': True},
{'date': '2020-06-03 10:10',
'a': 'MINIMUMINTERVAL',
'b': 0.0,
'c': True},
{'date': '2020-06-03 10:15',
'a': 'MINIMUMINTERVAL',
'b': 0.0,
'c': True},
{'date': '2020-06-03 10:20',
'a': 'MINIMUMINTERVAL',
'b': 0.0,}
]}
I want to transfer it to a dataframe object, like this:
rdd = sc.parallelize([test])
jsonDF = spark.read.json(rdd)
This results in a corrupted record. From my understanding the reason for this is, that True and False can't be entries in Python. So I need to tranform these entries prior to the spark.read.json() (to TRUE, true or "True"). test is a dict and rdd is a pyspark.rdd.RDD object. For a datframe object the transformation is pretty straigth forward, but I didn't find a solution for these objects.
spark.read.json expects an RDD of JSON strings, not an RDD of Python dictionaries. If you convert the dictionary to a JSON string, you should be able to read that into a dataframe:
import json
df = spark.read.json(sc.parallelize([json.dumps(test)]))
Another possible way is to read in the dictionary using spark.createDataFrame:
df = spark.createDataFrame([test])
which will give a different schema with maps instead of structs.

How to get all the JSON values for the same keys iterated number of times using groovy?

def json = '{"book": [{"id": "01","language": "Java","edition": "third","author": "Herbert Schildt"},{"id": "07","language": "C++","edition": "second","author": "E.Balagurusamy"}]}'
Using Groovy code, how to get the "id" values printed for "book" array?
Output:
[01, 07]
This is the working example using your input JSON.
import groovy.json.*
def json = '''{"book": [
{"id": "01","language": "Java","edition": "third","author": "Herbert Schildt"},
{"id": "07","language": "C++","edition": "second","author": "E.Balagurusamy"}
]
}'''
def jsonObj = new JsonSlurper().parseText(json)
println jsonObj.book.id // This will return the list of all values of matching key.
Demo here on groovy console : https://groovyconsole.appspot.com/script/5178866532352000

python3: Extract same type value from Json file

The following is my Json file which is decoded on base64.
response={"response": [{"objcontent": [{"title": "Pressure","rowkeys": [
"lat",
"lon",
"Pressure"
],
"rowvalues": [
[
"WxsArK0NV0A=",
"uaQCWFxSM0A=",
"ncvggc7lcUA6MVVLnZiMQH6msaA+0yhANzLp2RsZhkBwobfXt9BXQKtxbnjV+IFARq3fVqOWiEBwyyvmt+V9QDGg7k8YUHpA4IZm9W/De0A="
],
[
"WxsArK0NV0A=",
"HqJT4w7RUkA=",
"BfPox4I5ikCLVYxUxWqIQIFwlJFA+IVAJeQ6gBLyhEBB0QlkoGiCQDOkvnAZUm1AkGbWKEgza0A+FCkwH4phQHwSRSY+iVRAKcvC4pRliEA="
],
[
"WxsArK0NV0A=",
"G5rYdw0NXkA=",
"C9dhhIVrg0B2hCvzOoKKQMrMWhll5o5AIujgxBB0ZkD8+EipfXx0QOXh0LLycH5ATdtxKqbtdkAw66X3l/VhQLqvZBbd13FAjKl2+8UUjUA="
],
[
"WxsArK0NV0A=",
"PTvsm55daEA=",
"W+wyHC12dUCrvSLM1d6BQMfay0ZjbYpAjnk4Ecc8dkDH35pL429xQPTOwkF6Z41Aci5JATkXjUBQ6Wjlp3RQQFlpNGmsNHpAFf0DUor+dUA="
]]}]}]}
I decoded the values and use these values to draw a plot.following is the code.
import base64
import struct
import numpy as np
import pylab as pl
for response_i in response['response']:
for row in response_i['objcontent'][0]['rowvalues']:
for item in row[:]:
decoded=base64.b64decode(item)
if len(decoded)<9:
a=struct.unpack('d',decoded)
else:
decoded=base64.b64decode(item)
a=struct.unpack('10d',decoded)
last=np.array(a)
pl.show(pl.plot(last))
but i would like to saparate the value of each list. in the 'row keys' there are 3 elements [ "lat", "lon", "Pressure"] accordingly there are 3 values in each list of rowvalues.
My question is how can I separate the different values in rowvalues and add them in each group of rowkeys.
so, at the end I suppose to have 3 list which included all the decoded values.
'lat': [WxsArK0NV0A=,WxsArK0NV0A=,WxsArK0NV0A=,WxsArK0NV0A=]
'lon': [uaQCWFxSM0A=,HqJT4w7RUkA=,G5rYdw0NXkA=,PTvsm55daEA=]
'pressure': [ncvggc7lcUA6MVVLnZiMQH6msaA+0yhANzLp2RsZhkBwobfXt9BXQKtxbnjV+IFARq3fVqOWiEBwyyvmt+V9QDGg7k8YUHpA4IZm9W/De0A=, BfPox4I5ikCLVYxUxWqIQIFwlJFA+IVAJeQ6gBLyhEBB0QlkoGiCQDOkvnAZUm1AkGbWKEgza0A+FCkwH4phQHwSRSY+iVRAKcvC4pRliEA=, C9dhhIVrg0B2hCvzOoKKQMrMWhll5o5AIujgxBB0ZkD8+EipfXx0QOXh0LLycH5ATdtxKqbtdkAw66X3l/VhQLqvZBbd13FAjKl2+8UUjUA=, W+wyHC12dUCrvSLM1d6BQMfay0ZjbYpAjnk4Ecc8dkDH35pL429xQPTOwkF6Z41Aci5JATkXjUBQ6Wjlp3RQQFlpNGmsNHpAFf0DUor+dUA=]
One approach would be to manually sort the data, like so:
from collections import defaultdict
from base64 import b64decode
import json
d = defaultdict(list)
js = ''
with open(json_file) as f:
js = b64decode(f.read()).decode()
js = json.loads(js)
response = js['response']['obj_content'][0]
for i, col_name in enumerate(response['row_keys']):
for row_val in ['row_values']:
d[col_name].append(row_val[i])
defaultdict automatically creates a new list when a key is called that previously didn't exist, which makes your code slightly sleeker.
Another option would be to use pandas.DataFrame and load data like so:
import pandas as pd
response = json_file['response']['obj_content'][0]
df = pd.DataFrame(response['row_values'], columns= response['row_keys'])
The neat thing about pandas is, that it's quite expansive in its features; for example, you could plot your data using the previously created DataFrame like so:
df.plot()

groovy.json.JsonSlurper parse JSON

I'm trying to parse a JSON-File in my gradle task.
CODE:
def jsonFile = "../files/json/myJSON.json"
def list = new JsonSlurper().parseText(jsonFile)
JSON - FILE
{
"prepare": {
"installed": [],
"uninstalled": []
},
"config": {
"files": []
}
}
But the code gives me the following exception:
Lexing failed on line: 1, column: 1, while reading '.', no possible valid JSON value or punctuation could be recognized.
And I don't understand why, I also validated my JSON-File on http://jsonlint.com/ and it says that it is a valid JSON!
Above code is trying to parse the string ../files/json/myJSON.json as JSON. Instead use:
def jsonFile = new File("../files/json/myJSON.json")
def map = new JsonSlurper().parse(jsonFile)