This is my serializer.py
class RefbookSerializer(serializers.ModelSerializer):
class Meta:
model = Refbook
fields = ['id', 'code', 'name']
And it's my views.py
class RefbookAPIList(ListCreateAPIView):
queryset = Refbook.objects.all()
serializer_class = RefbookSerializer
def get_queryset(self):
date = self.request.query_params.get('date', None)
if date:
query = Refbook.objects.filter(versions__date__lte=date).distinct()
return query
return super().get_queryset()
Now, on request
GET api/v1/refbooks/?date=2023-02-01
it returns a response like:
[
{
"id": 3,
"code": "1",
"name": "..."
},
{
"id": 4,
"code": "2",
"name": "..."
}
]
But i want like this:
{
"refbooks": [
{
"id": 3,
"code": "1",
"name": "..."
},
{
"id": 4,
"code": "2",
"name": "..."
}
]
}
How can i add this "refbooks" key and curly braces around it?
Related
Trying to achieve this by using the following script, which I want to extend with a loop to loop through the input. This should filter on the objects with have the value "valse", the others should be deleted/replaced.
def Message processData(Message message) {
//getBody & new jsonSlurper
def body = message.getBody(java.lang.String) as String
def data = new JsonSlurper().parseText(body)
if (data.value != "false") {
body = body.replaceAll(~/^(.*?)\childNodes/, "")
message.setBody(body);
} else {
}
return message
}
Input:
[{
"name": "1",
"value": "true",
"childNodes": [{
"name": "2",
"value": "true",
"childNodes": [{
"name": "3",
"value": "false",
"childNodes": [{
"name": "4",
"value": "false"
}]
}]
}]
}]
Desired output:
[{
"name": "3",
"value": "false",
"childNodes": [{
"name": "4",
"value": "false"
}]
}]
import groovy.json.*
def body ='''
[{
"name": "1",
"value": "true",
"childNodes": [{
"name": "2",
"value": "true",
"childNodes": [{
"name": "3",
"value": "false",
"childNodes": [{
"name": "4",
"value": "false"
}]
}]
}]
}]
'''
def filter(arr){
for(i in arr){
if(i.value == 'false') return [i]
def filteredChild = filter(i.childNodes)
if(filteredChild)return filteredChild
}
return null // not found
}
def filtered = filter( new JsonSlurper().parseText(body) )
println new JsonBuilder(filtered).toPrettyString()
Assuming you have only a single child object every time and that your task is finding the first value=false node and returning it with all the child nodes, you can do the following:
def processData(String message) {
def data = new JsonSlurper().parseText(message)[0]
while (data.value != 'false') { data = data.childNodes[0] }
return new JsonBuilder([data]).toPrettyString()
}
Here's a Spock test to go with it (replaced pretty string with regular json string so that it's easier to compare strings with ==)
class ParseSpec extends Specification {
def testString = '''
[{
"name": "1",
"value": "true",
"childNodes": [{
"name": "2",
"value": "true",
"childNodes": [{
"name": "3",
"value": "false",
"childNodes": [{
"name": "4",
"value": "false"
}]
}]
}]
}]
'''
def processData(String message) {
def data = new JsonSlurper().parseText(message)[0]
while (data.value != 'false') { data = data.childNodes[0] }
return JsonOutput.toJson([data])
}
def 'run test'() {
expect:
'''[{"name":"3","value":"false","childNodes":[{"name":"4","value":"false"}]}]''' == processData(testString)
}
}
I am converting a two-dimensional array into a JSON object.
Now my controller returning this output:
[
[
{
"id": 1,
"title": "V1",
"project_id": 1
}
],
[]
]
Want to convert it like:
[
{
"id": 1,
"name": "Laravel"
},
{
"id": 2,
"name": "Wordpress"
}
]
My controller code:
$user = auth()->user();
$projectVersions = array();
foreach($user->projects as $project)
{
$projectId = $project->pivot->project_id;
$projectVersions[] = Version::where('project_id', $projectId)
->where('created_by', $user->id)
->get();
}
return $projectVersions;
When I am using below code which is suggested by #John Lobo, it is returning below output:
{
"id": 2,
"name": "Hadayat Niazi",
"email": "niazicr801#gmail.com",
"is_admin": 0,
"email_verified_at": null,
"created_at": "2021-06-11T15:13:00.000000Z",
"updated_at": "2021-06-11T15:13:00.000000Z",
"projects": [
{
"id": 1,
"name": "Laravel",
"pivot": {
"user_id": 2,
"project_id": 1
},
"versions": [
{
"id": 1,
"title": "V1"
}
]
}
]
}
Displaying the user projects and versions:
Again I am updating the code for #John Lobo, he want to look the output
$user = User::with(['projects', 'projects.versions'])
->find(auth()->user()->id);
$result = $user->projects->map(function ($project) {
return [
$project->versions,
];
});
return $result;
Output the code
[
[
[
{
"id": 1,
"title": "V1",
"project_id": 1,
"version": "1.22",
"created_by": 2,
"is_publish": 0,
"feature": "<b>In this ipdate asdsdasd</b>",
"bug_fix": "<p><b>sdfdffffffffff</b></p>",
"created_at": "2021-06-12T08:08:21.000000Z",
"updated_at": "2021-06-12T08:08:21.000000Z"
},
{
"id": 2,
"title": "v2",
"project_id": 1,
"version": "2.12",
"created_by": 2,
"is_publish": 0,
"feature": "adsdasdsadas",
"bug_fix": "sddasdas",
"created_at": null,
"updated_at": null
}
]
],
[
[]
]
]
In controller you can do the following.if you have relation in project model called version
$projectVersions=User::with(['projects','projects.version'])->find(auth()->user()->id);
return $projectVersions->projects;
I believe Project model has below relationship
public function version(){
return $this->hasMany(Version::class);
}
Updated
$user=User::with(['projects','projects.versions'])->find(auth()->user()->id);
$result = $user->projects->map(function ($project) {
return $project->versions;
});
dd($result);
Use like below
$json = json_encode($responseOfController);
echo "<pre>";print_r($json);die;
I use Yii2 and I created RESTful API service. But in my app I want to return JSON data with predefined key for all responses. For example:
Default respons:
[
{
"id": 1,
"title": "Brooklyn"
},
{
"id": 2,
"title": "Financial District"
},
{
"id": 4,
"title": "Social District"
}
]
But I want to get smth like that:
"data": [
{
"id": 1,
"title": "Brooklyn"
},
{
"id": 2,
"title": "Financial District"
},
{
"id": 4,
"title": "Social District"
}
]
You should simply customize rest serializer, in your controller :
public $serializer = [
'class' => 'yii\rest\Serializer',
'collectionEnvelope' => 'data',
];
Read more.
I am new to groovy and need to parse JSON response. the response looks like this:
[
{
"name": "John",
"start_date": "2016-09-30",
"sort_order": 1
},
{
"name": "Tony",
"start_date": "2016-06-30",
"sort_order": 2
}
]
How can I get each object from that? would like to end up with name, start_date and sort_order for each student together.
You would use JsonSlurper
import groovy.json.*
def json = '''[
{ "name": "John", "start_date": "2016-09-30", "sort_order": 1 },
{ "name": "Tony", "start_date": "2016-06-30", "sort_order": 2 } ]'''
def parsed = new JsonSlurper().parseText(json)
assert parsed.name == ['John', 'Tony']
I'm trying to write extract the name value "Acura" from a JSON array response by using the location of the value stored in a variable called "jsonFieldName".
Below is the code that I'm trying to do this with, however, everytime i run the script, SOAPUI returns error: "java.lang.NullPointerException: Cannot get property 'name' on null object error at line: 156"
Can someone kindly advise how to do this?
import groovy.json.JsonSlurper
def response = '''{
"makes": [
{
"id": 200002038,
"name": "Acura",
"niceName": "acura",
"models": [
{
"id": "Acura_ILX",
"name": "ILX",
"niceName": "ilx",
"years": [
{
"id": 200471908,
"year": 2014
}
]
},
{
"id": "Acura_ILX_Hybrid",
"name": "ILX Hybrid",
"niceName": "ilx-hybrid",
"years": [
{
"id": 200493809,
"year": 2014
}
]
},
{
"id": "Acura_MDX",
"name": "MDX",
"niceName": "mdx",
"years": [
{
"id": 200465929,
"year": 2014
}
]
},
{
"id": "Acura_RDX",
"name": "RDX",
"niceName": "rdx",
"years": [
{
"id": 200467168,
"year": 2014
}
]
},
{
"id": "Acura_RLX",
"name": "RLX",
"niceName": "rlx",
"years": [
{
"id": 100539511,
"year": 2014
}
]
},
{
"id": "Acura_TL",
"name": "TL",
"niceName": "tl",
"years": [
{
"id": 200488448,
"year": 2014
}
]
},
{
"id": "Acura_TSX",
"name": "TSX",
"niceName": "tsx",
"years": [
{
"id": 200490517,
"year": 2014
}
]
},
{
"id": "Acura_TSX_Sport_Wagon",
"name": "TSX Sport Wagon",
"niceName": "tsx-sport-wagon",
"years": [
{
"id": 200673755,
"year": 2014
}
]
}
]
},
{
"id": 200001769,
"name": "Aston Martin",
"niceName": "aston-martin",
"models": [
{
"id": "Aston_Martin_DB9",
"name": "DB9",
"niceName": "db9",
"years": [
{
"id": 200473436,
"year": 2014
}
]
},
{
"id": "Aston_Martin_Rapide_S",
"name": "Rapide S",
"niceName": "rapide-s",
"years": [
{
"id": 200460643,
"year": 2014
}
]
},
{
"id": "Aston_Martin_V8_Vantage",
"name": "V8 Vantage",
"niceName": "v8-vantage",
"years": [
{
"id": 200472947,
"year": 2014
}
]
},
{
"id": "Aston_Martin_Vanquish",
"name": "Vanquish",
"niceName": "vanquish",
"years": [
{
"id": 200431313,
"year": 2014
}
]
}
]
}
],
"makesCount": 2
}'''
def jsonFieldName = ('makes[0].name')
def json = new JsonSlurper().parseText (response)
jsonFieldName.split("\\.").each{json = json[it]}
assert json == 'Acura'
Assuming that your JSON is good from the response (check by calling print) Try adding .text to the end of your jsonSlurper() Call
It also looks like you have a space between parseText and (response)
so it should be
def json = new JsonSlurper().parseText(response)
However I would try casting to ArrayList<LazyMap> to ensure you can iterate by
ArrayList<LazyMap> json = new JsonSlurper().parseText(response) as ArrayList<LazyMap>
Then call :
json.get('Acura')
This line of your code doesn't handle the index resolution:
jsonFieldName.split("\\.").each{json = json[it]}
There is no key with the name makes[0]. Instead there is an array of makes and you are interested on the first one. The following hardcoded line retrieves the name attribute:
def result = json.'makes'[0].'name'
As you can see here there is an additional step to resolve the index operator. Of course you can implement this functionality on your own or use JsonPath instead of JsonSlurper.
OK so I managed to get this working by using JsonPath instead of JsonSlurper.
To achieve this I had to import the following:
import com.jayway.jsonpath.JsonPath
def jsonFieldName = "makes[0].name"
def expectedValue = "Acura"
def jsonSuff = JsonPath.read(response, jsonFieldName)
log.info(jsonSuff)
if (jsonSuff.toString() == expectedValue.toString()){
log.info("Actual value"+jsonSuff+"is equal to expected value"+expectedValue)
}