In PHP when I want to give a name to an array of json objects I use this line.
$json = json_encode(array("users" => $output));
And this variable would be printed like this.
{"users":[{"user_id":"1"}
But now, I'm building a project in Node.js and I need to give a name to an array, and I don't know how to do it, I'm printing data using this line:
res.send(JSON.stringify(users, null, 4));
[ { "user_id": "1" }, { "user_id": "2" } ]
Thank you.
Just build the object with "root" key users before stringify
res.send( JSON.stringify( { 'users': users } , null, 4) );
You can send json directly specifying data points
res.json({ variablename : thevalue (in your case array)})
if more than one value, just follow the syntax
res.json({ variablename : thevalue1, variablename : value2)})
You can something like this:
{'users': JSON.stringify(users, null, 4)}
Related
Here is my json data:
{
"TransactionId": "1",
"PersonApplicant": [
{
"PersonalId": "1005",
"ApplicantPhone": [
{
"PhoneType": "LANDLINE",
"PhoneNumber": "8085063644",
"IsPrimaryPhone": true
}
]
},
{
"PersonalId": "1006",
"ApplicantPhone": [
{
"PhoneType": "LANDLINE",
"PhoneNumber": "9643645364",
"IsPrimaryPhone": true
},
{
"PhoneType": "HOME",
"PhoneNumber": "987654321",
"IsPrimaryPhone": false
}
]
}
]
}
I want to get phone no of the people who have phonetype as landline.
How to do that?
I tried this approach:
#find phoneNumber when phoneType='LANDLINE'
SELECT
#path_to_name := json_unquote(json_search(applicationData, 'one', 'LANDLINE')) AS path_to_name,
#path_to_parent := trim(TRAILING '.PhoneType' from #path_to_name) AS path_to_parent,
#event_object := json_extract(applicationData, #path_to_parent) as event_object,
json_unquote(json_extract(#event_object, '$.PhoneNumber')) as PhoneNumber
FROM application;
The issue with this is that I am using 'one' so I am able to achieve results but here in my json I have 2 people who have type as landline.
Using json search I am getting array of values and I am not able to decide how to extract these array row values in a manner where I can extract paths.
SELECT
#path_to_name := json_unquote(json_search(applicationData, 'all', 'LANDLINE')) from application;
result:
as you can see at 3rd and 4th row i am getting 2 data as an array.
How do I store this data to get the appropriate result?
I also tried one more query but not able to retrieve results for array of data.
I cannot use stored procedure and I have to use mysql workbench.
Please note that I am fresher so I don't know how I can approach this solution for more complex queries where I may have to retrieve id of a person having type as landline (multiple people in single array).
SELECT test.id, jsontable.*
FROM test
CROSS JOIN JSON_TABLE(test.data,
'$.PersonApplicant[*]'
COLUMNS ( PersonalId INT PATH '$.PersonalId',
PhoneType VARCHAR(255) PATH '$.ApplicantPhone[0].PhoneType',
PhoneNumber VARCHAR(255) PATH '$.ApplicantPhone[0].PhoneNumber')) jsontable
WHERE jsontable.PhoneType = 'LANDLINE';
https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=4089207ccfba5068a48e06b52865e759
I'm trying to create a variable from an aggregate query in MongoDB and then use it to make another query.
var test_var = db.d_snapshot4.aggregate([{$group : {_id: null,
max_snapshot_date: {$max:"$snapshot_date"},
max_snapshot_date_str:
{$max:"$snapshot_date_str"}
}
}
]);
The content of test_var is as follows:
{
"_id": null,
"max_snapshot_date": ISODate("2020-05-31T00:00:00.000Z"),
"max_snapshot_date_str": "20200531"
}
But when I try to see the result of test_var.max_snapshot_date I get nothing back.
I need to use the variable as follows:
db.d_snapshot4.aggregate([{$match: {"snapshot_date": {$gte: test_var.max_snapshot_date } }}]);
Any suggestions?
Thanks,
Dina
Did you try with test_var["max_snapshot_date"]? Or do you get any error?
I am studying quasar at the moment, and I want to know how to export a table to JSon. I have data in JSonimported and I want to get output in JSon too.
Now I'm using JSON.stringify to get data of my table, but that gives all data in a single line in JSon.
Here's a piece of my code in quasar :
exportTable() { const status = exportFile('table.json', JSON.stringify(this.data), 'text/json')}
and it gives me :
[{"Name":"xxx","Adress":"xxx","Zip code":"xxx"},{"Name":"yyy","Adress":"yyy","Zip code":"yyy"}]
What I want to output :
[{
"Name":"xxx",
"Adress":"xxx",
"Zip code":"xxx"
},
{
"Name":"yyy",
"Adress":"yyy",
"Zip code":"yyy"
}]
How can I get this ?
If I understood correctly, you want to use:
JSON.stringify(this.data, null, 4)
Where the last argument (4) is the spacing you desire.
You can have a look at JSON.stringify official documentation
const data = [{"Name":"xxx","Adress":"xxx","Zip code":"xxx"},{"Name":"yyy","Adress":"yyy","Zip code":"yyy"}]
console.log(JSON.stringify(data, null, 4))
python for loop:
actions = json_data['actions']
for a in actions:
if 'causes' in a:
for cause in a['causes']:
if 'userId' in cause:
self.user = cause['userId']
How do I do this in groovy?
def jenkins_data = new JsonSlurper().parseText(obj)
Using this json, I'm not sure how to drill down to grab userId. I imagine I need to use a for loop to check for each element in the list for the 'cause' key and then repeat for the 'userId' key.
Here is an example payload I'm dealing with.
self.payload_a = {"number": 3585, "url": "https://test.m.test.com/job/gfdsgdsf/3585/",
"displayName": "master_3585", "timestamp": 1516992464686,
"actions": [{"something": "nothing"}, {"causes": [{"userId": "build"}]}]}
Using an example payload I am able to to echo jenkins_data.actions.causes and see output
however echoing jenkins_data.actions.causes.userId is null (even though the userId is definitely in the payload)
When I run
echo jenkins_data.actions.causes
I get
[null, [[_TestIdCause, shortDescription:Started by user, B, userId:valueweneed, userName:test, B]], null, null, null, null, null, null, null, null, null, null, null, null, null, null]
The answer is yes . You need to put a loop to traverse all nodes in json.
Parsing json is quire complex.
According to Json : Any data type can be returned from a same node like ('userId') while traversing. like shown below
"userId" : "A"
...
"userId" : { ... }
...
"userId" : [ ... ]
You need to handle this return data as per you wish. As you ask in the question to get the userId node, just use the xpath like shown below
def json = new JsonSlurper().parseText(jsontxt)
println json.actions.causes.userId
In your case it returns list. so just flatten it.
println json.actions.causes.userId.flatten()
I am new to mySQL and I need help extracting values from a Json variable.
Please see the example bellow.
#Model ='{
"SortOptions": [{
"SortBy": "[FirstName]",
"SortDir": "DESC"
},
{
"SortBy": "[LastName]",
"SortDir": "DESC"
}
]
}';
I need to extract SortBy and SortDir Key values and create an expression .Expected result
#SortOptions = '[FirstName] DESC [LastName] DESC'
You can extract information from a JSON using JSON_EXTRACT.
https://dev.mysql.com/doc/refman/5.7/en/json.html#json-paths