I have a SQL table that contains a column holding JSON data. One of the JSON values looks as follows:
{
"_id": "5a450f038104ca3cb0ff74b5",
"index": 3,
"guid": "20d807c5-bddc-44b9-97fe-fd18af1b6066",
"isActive": false,
"balance": "$2,832.38",
"picture": "http://placehold.it/32x32",
"age": 23,
"eyeColor": "brown",
"firstname": "Genevieve",
"lastname": "Green",
"gender": "female",
"company": "PROFLEX",
"email": "genevievegreen#proflex.com",
"phone": "+1 (919) 464-2866",
"address": "107 Clermont Avenue, Rew, California, 4298",
"about": "Magna pariatur ut enim nulla pariatur ad Lorem amet. Proident nulla exercitation id Lorem commodo minim cillum irure exercitation labore nostrud nostrud sint. Voluptate commodo ea commodo quis Lorem laborum culpa voluptate enim nulla enim duis.\r\n",
"registered": "2016-02-16T09:51:25 +05:00",
"latitude": -16.492643,
"longitude": -71.782118,
"tags": [
"in",
"non",
"eiusmod",
"labore",
"dolor",
"laboris",
"ullamco"
],
"friends": [
{
"id": 0,
"name": "Mccoy Berg",
"interests": [
"Music",
"Birding",
"Chess"
]
},
{
"id": 1,
"name": "Chase Mcfadden",
"interests": [
"Software",
"Chess",
"History"
]
},
{
"id": 2,
"name": "Michele Dodson",
"interests": [
"Football",
"Birding",
"Movies"
]
}
],
"greeting": "Hello, Genevieve! You have 2 unread messages.",
"favoriteFruit": "strawberry"
}
I can execute a query that retrieves the first and last name and all the friends as follows:
SELECT
JSON_VALUE(JsonValue, '$.firstname') as FirstName,
JSON_VALUE(JsonValue, '$.lastname') as LastName,
JSON_QUERY(JsonValue, '$.friends') as FriendsList,
From <MyTable>
Where JSON_VALUE(JsonValue,'$.lastname') = 'Green'
The query, as written, returns a JSON string for FriendsList that looks like this:
[
{
"id":0,
"name":"Mccoy Berg",
"interests":[
"Music",
"Birding",
"Chess"
]
},
{
"id":1,
"name":"Chase Mcfadden",
"interests":[
"Software",
"Chess",
"History"
]
},
{
"id":2,
"name":"Michele Dodson",
"interests":[
"Football",
"Birding",
"Movies"
]
}
]
What I would actually like is just an array of friends names, something like this:
["Mccoy Berg", "Chase Mcfadden", ...]
I'm sure this is possible but my knowledge of JSON is limited.
SQL server is kind of funny when it comes to creating arrays in the format you are expecting. By default, it always creates JSON arrays as key:value pairs. You can work around this by using STUFF() and FOR XML when working with JSON.
You first create a subquery that returns only the names, then you can STUFF those names into the FriendsList field, like so:
SELECT
FirstName = JSON_VALUE(JsonValue, '$.firstname')
,LastName = JSON_VALUE(JsonValue, '$.lastname')
,FriendsList = '[' + STUFF(
(SELECT ',' + '"' + [name] + '"'
FROM OPENJSON(JsonValue,'$.friends')
WITH ( [name] NVARCHAR(100) '$.name')
FOR XML PATH (''))
, 1, 1, '')
+ ']'
FROM <MyTable>
Related
I has table Books, Discount with relationship is 1-n, so when i load api url like {{APP_URL}}/api/books?isSale=true so it will return a json data about book object with key discount must has value, but it return all of them.
My code of BookResource like
class BookResource extends JsonResource
{
/**
* Transform the resource into an array.
*
* #param \Illuminate\Http\Request $request
* #return array|\Illuminate\Contracts\Support\Arrayable|\JsonSerializable
*/
public function toArray($request)
{
return [
'id' => $this->id,
'category_id' => $this->category_id,
'book_title' => $this->book_title,
'book_summary'=>$this->book_summary,
'book_cover_photo'=>$this->book_cover_photo,
'discount' => DiscountResource::collection($this->whenLoaded('discount'))
];
}
}
my method index in BookController
public function index(Request $request)
{
$filter = new BooksFilter();
$filterItems = $filter->transform($request);
$isSale = $request->query('isSale');
$books = Book::where($filterItems);
if($isSale){
$books = $books->with('discount');
}
return new BookCollection($books->paginate()->appends($request->query()));
}
so when i call api {{APP_URL}}/api/books?isSale=true i want return json from this
"data": [
{
"id": 1,
"category_id": 1,
"book_title": "Est est sapiente ut enim et.",
"book_summary": "Gryphon. 'Well, I shan't go, at any rate,' said Alice: 'besides, that's not a bit of the table, but there was no use denying it. I suppose it doesn't matter a bit,' she thought it would,' said the.",
"book_cover_photo": "book9",
"discount": []
},
{
"id": 2,
"category_id": 1,
"book_title": "Maiores consequatur optio quos distinctio optio inventore.",
"book_summary": "Suddenly she came upon a little bottle on it, ('which certainly was not easy to take out of the evening, beautiful Soup! Soup of the water, and seemed not to lie down on her spectacles, and began.",
"book_cover_photo": "book9",
"discount": [
{
"id": 1,
"book_id": 2,
"discount_start_date": "2022-10-12",
"discount_end_date": null,
"discount_price": "42.38"
}
]
},
to this
"data": [
{
"id": 2,
"category_id": 1,
"book_title": "Maiores consequatur optio quos distinctio optio inventore.",
"book_summary": "Suddenly she came upon a little bottle on it, ('which certainly was not easy to take out of the evening, beautiful Soup! Soup of the water, and seemed not to lie down on her spectacles, and began.",
"book_cover_photo": "book9",
"discount": [
{
"id": 1,
"book_id": 2,
"discount_start_date": "2022-10-12",
"discount_end_date": null,
"discount_price": "42.38"
}
]
},
I can parse in my code json file like below. It works fine:
[
{
"albumId": 1,
"id": 1,
"title": "Accusamus beatae ad facilis cum similique qui sunt",
"url": "https://via.placeholder.com/600/92c952",
"thumbnailUrl": "https://via.placeholder.com/150/92c952",
"publishDate": "2021-03-12"
},
{
"albumId": 1,
"id": 2,
"title": "Reprehenderit est deserunt velit ipsam",
"url": "https://via.placeholder.com/600/771796",
"thumbnailUrl": "https://via.placeholder.com/150/771796",
"publishDate": "2021-03-12"
}
]
but i need to update my json file to be able to present data from a specific parent. In this example: position1 or position 2.
{
"position1":[
{
"albumId": 1,
"id": 1,
"title": "Accusamus beatae ad facilis cum similique qui sunt",
"url": "https://via.placeholder.com/600/92c952",
"thumbnailUrl": "https://via.placeholder.com/150/92c952",
"publishDate": "2021-03-12"
},
{
"albumId": 1,
"id": 2,
"title": "Reprehenderit est deserunt velit ipsam",
"url": "https://via.placeholder.com/600/771796",
"thumbnailUrl": "https://via.placeholder.com/150/771796",
"publishDate": "2021-03-12"
}
],
"position2":[
{
"albumId": 1,
"id": 1,
"title": "Accusamus beatae ad facilis cum similique qui sunt",
"url": "https://via.placeholder.com/600/92c952",
"thumbnailUrl": "https://via.placeholder.com/150/92c952",
"publishDate": "2021-03-12"
},
{
"albumId": 1,
"id": 2,
"title": "Reprehenderit est deserunt velit ipsam",
"url": "https://via.placeholder.com/600/771796",
"thumbnailUrl": "https://via.placeholder.com/150/771796",
"publishDate": "2021-03-12"
}
]
}
My code looks like below. What should I do to list only children items from ex: position1.
Future<List<Photo>> fetchPhotos(http.Client client) async {
final response = await client
.get(Uri.parse('https://jsonplaceholder.typicode.com/photos'));
return compute(parsePhotos, response.body);
}
// A function that converts a response body into a List<Photo>.
List<Photo> parsePhotos(String responseBody) {
final parsed = jsonDecode(responseBody).cast<Map<String, dynamic>>();
return parsed.map<Photo>((json) => Photo.fromJson(json)).toList();
}
and
body: FutureBuilder<List<Photo>>(
future: fetchPhotos(http.Client()),
builder: (context, snapshot) {
if (snapshot.hasError) print(snapshot.error);
return snapshot.hasData
? PhotosList(photos: snapshot.data!)
: Center(child: CircularProgressIndicator());
},
),
I am writing an api to fetch data. I have three models Page , Section and Question.This is image of the erd diagram showing relationship between different entities .
I have defined there relationships in respective models.
Page Model
class CmsPage extends ActiveRecord
{
public static function tableName()
{
return '{{%cms_page}}';
}
public function getCmsSection()
{
/*Page and Section has many to many relation having a junction table*/
return $this->hasMany(CmsSection::className(),['id'=>'section_id'])->viaTable('tbl_cms_page_section',['page_id'=>'id']);
}
}
Section Model
class CmsSection extends ActiveRecord
{
public static function tableName()
{
return '{{%cms_section}}';
}
public function getCmsQuestion()
{
return $this->hasMany(CmsQuestion::className(),['id'=>'section_id']);
}
}
Question Model
class CmsQuestion extends ActiveRecord
{
public static function tableName()
{
return '{{%cms_question}}';
}
public function getCmsSection()
{
return $this->hasOne(CmsSection::className(),['section_id'=>'id']);
}
}
I want to fetch data as a json object like below
{
"id": "1",
"name": "Lorem Ipsom",
"title": "Eiusmod voluptate Lorem aute tempor fugiat eiusmod ex ipsum enim magna consequat cupidatat.",
"short_summary": "Will ContentsQuis consequat occaecat consequat aliquip adipisicing aute sunt pariatur culpa sint consectetur reprehenderit eu aliquip.",
"summary": "Officia eu fugiat quis laboris voluptate sunt sint cupidatat eu consequat et deserunt sint eu.",
"section": [
{
"id": 1,
"title": "Advanced Planning",
"short_summary": "Advanced Planning",
"summary": "Summary ",
"question": [
{
"id": 1,
"question_type_id": 1,
"show_relations": "true",
"title": "Family Members",
"place_holder_text": "Your faimly list is currently empty.",
"label_name": "Name",
"label_email": "Email",
"label_phone": "Mobile number",
"select_1": "url:test-data/dashboard-relationship.json",
"label": "Remarks"
},
{
"id": 2,
"question_type_id": 2,
"title": "Close Friends",
"place_holder_text": "Your list is close friends currently empty.",
"label_name": "Name",
"label_email": "Email",
"label_phone": "Mobile number",
"label_address": "Address",
"help_text": "<b>Close Friends<b><ul><li>1</</li><li>2</</li></ul>"
},
{
"id": 3,
"question_type_id": 3,
"title": "Designated Executors",
"place_holder_text": "It is vital you nominate an Executor",
"label_name": "Name",
"label_email": "Email",
"label_phone": "Mobile number",
"label_address": "Address"
},
{
"id": 4,
"question_type_id": 4,
"question_type": {},
"title": "Witnesses",
"place_holder_text": " It is vital you nominate an Executor",
"label_1": "Name",
"opption_2": "Email",
"label_3": "Phone",
"label_4": "Occupation",
"label": "Address"
}
]
},
{
"id": 2,
"title": "Labore proident cupidatat ex dolore occaecat in tempor sit proident sint labore minim cillum.",
"summary": "Dolor cupidatat consequat cillum deserunt laborum aliqua commodo occaecat sint aute cillum exercitation.",
"short_summary": "Ullamco Lorem incididunt dolore ipsum.",
"question": [
{
"id": 5,
"question_type_id": 5,
"title": "Last Words",
"short_summary": "Plan, the way you want!",
"summary": "Start by writing down.",
"label": "Write your last words here"
},
{
"id": 6,
"question_type_id": 5,
"title": "Venue",
"short_summary": "Plan, the way you want!",
"summary": "Start by writing down.",
"label": "Mention"
}
]
}
]
}
I have followed yii2 docs to come this far but not been able to get data in the json format. How to do that?
HI in API there a function call fields you can override that function :
Please check below code which will help you to get idea or for more detail
you read yii2 doc here
Yii 2 fields doc
public function fields()
{
return [
'id',
"name"
'title',
'short_summary',
'summary',
'section'=> function ($model) {
return $model->cmsSection;
},
];
}
if you want to go more nested then you can use array store first nested data and again use loop for inner data:
'section'=> function ($model) {
$sections = $model->cmsSection;
//store section data in array
//forloop of $sections
$sections->question;
//Again store question data in first array and return it
},
Aplly it you will understand what i am trying to tell you.
I am working a react blog app that list article and comment towards the article. I am using a JSON file to store data in the local.
I have added button to add new comment. I having trouble with adding the new comment to JSON data.
I have imported the data to my component file. I am stuck on how to update the JSON.
[{
"id": "5d403e5fbe39eb87471b8cd9",
"title": "laboris duis veniam",
"content": "Sint quis nisi tempor officia. occaecat pariatur sunt.\r\n",
"author":
{
"_id": "5d403e5f552ff12f1d0773d0",
"name": "Amanda Mckinney"
},
"comments": [
{
"id": "5d403e5f416a8a6b0447a069",
"content": "Do minim Culpa nostrud laborum consectet\r\n",
"commenter":
{
"_id": "5d403e5f58174caa22041e78",
"name": "Angelina Wong"
}
},
{
"id": "5d403e5f17475a36a4745241",
"content": "Velit reprehenderit et consectetur id in .\r\n",
"commenter":
{
"_id": "5d403e5f3511fa317d0bf561",
"name": "Gail Moss"
}
},
{
"id": "5d403e5f8419bad3767550b1",
"content": "Labore veniam dolor deserunt qui minim.\r\n",
"commenter":
{
"_id": "5d403e5f28bd1b5fc4d1be1b",
"name": "Staci Pierce"
}
},
{
"id": "5d403e5f43a52dd53b63f6c6",
"content": "Pariatur quis proident dolor veniam laborum.\r\n",
"commenter":
{
"_id": "5d403e5f33be38b996c4a8f1",
"name": "Mai Delaney"
}
},
{
"id": "5d403e5f9c53f6000ca12607",
"content": "Labore reprehenderit pariatur culpa non\r\n",
"commenter":
{
"_id": "5d403e5f1f77294e7fc77552",
"name": "Geraldine Gilliam"
}
}]
}]
In the comment session i want to add new comment object with details such as
{
"id": "5d403e5f9c53f6000ca12607",
"content": "Labore reprehenderit pariatur culpa non\r\n",
"commenter": {
"_id": "5d403e5f1f77294e7fc77552",
"name": "Geraldine Gilliam"
}
}
You can not write to a file of the machine in browser environment. You will have to use Node.js to achieve this.
I have json data structured in the following way from JsonPlaceholder API
'1': {
"userId": 1,
"id": 1,
"title": "sunt aut facere repellat",
"body": "quia et suscipit\nsuscipit"
}
I mapped the id as the key of the object and now want to return say objects '1' through '10' from the modified HTTP response shown above.
I tried using lodash _.pick():
_pick(object, ['1', '10']);
but that only returns object '1' and '10' instead of '1' through '10'
All help is appreciated thanks.
Have you considered just putting them in an array and then filtering it?
let data = [
{ id: 1 }, { id: 2 }, { id: 11 }
];
let filtered = data.filter(e => { return e.id >= 1 && e.id <= 10 });
console.dir(data);
console.dir(filtered);
if you can't and are stuck with them in a JSON object, maybe something like this that extracts the values first:
let json = {
'1': {
"userId": 1,
"id": 1,
"title": "sunt aut facere repellat",
"body": "quia et suscipit\nsuscipit"
},
'10': {
"userId": 10,
"id": 10,
"title": "sunt aut facere repellat",
"body": "quia et suscipit\nsuscipit"
},
'11': {
"userId": 11,
"id": 11,
"title": "sunt aut facere repellat",
"body": "quia et suscipit\nsuscipit"
}
};
var filtered =
Object
.keys(json).map(key => json[key])
.filter(val => val.id >= 1 && val.id <= 10);
console.dir(json);
console.dir(filtered);
Since you are already using lodash why not just use range to create an array of integers and then map over that too convert them to strings.
_.pick(object, _.range(1,10).map(_.toString));