Flutter - Parse Json with parent set - json

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());
},
),

Related

get nested json object containing all the related data in yii2

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.

How to update json file used for storing data for react blog app

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.

How to compare two JSON string in flutter?

I have two long JSON string and what I need is compare these strings and find if they are equals or not, if it's not equal I can get list1 which contains (JSON1-JSON2) and list2 contains (JSON2-JSON1)
I find this ( https://github.com/google/dart-json_diff ) but it's very annoying and I don't know how to use this
I mean something like this
final json1 = await http.get('https://jsonplaceholder.typicode.com/posts');
final json2 = await http.get('https://jsonplaceholder.typicode.com/posts');
var list1= compare(json1,json2);
var list2= compare(json2,json1);
List<dynamic> compare (List<dynamic> json1,List<dynamic> json1){
.
.
code?
.
.
return results;
}
/////////////////
json1=[
{
"userId": 1,
"id": 1,
"title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
"body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
},
{
"userId": 1,
"id": 2,
"title": "qui est esse",
"body": "est rerum tempore vitae\nsequi sint nihil reprehenderit dolor beatae ea dolores neque\nfugiat blanditiis voluptate porro vel nihil molestiae ut reiciendis\nqui aperiam non debitis possimus qui neque nisi nulla"
},
{
"userId": 1,
"id": 3,
"title": "ea molestias quasi exercitationem repellat qui ipsa sit aut",
"body": "et iusto sed quo iure\nvoluptatem occaecati omnis eligendi aut ad\nvoluptatem doloribus vel accusantium quis pariatur\nmolestiae porro eius odio et labore et velit aut"
},
]
/////////////////
json2=[
{
"userId": 1,
"id": 1,
"title": "sunt aut facere repellat ",
"body": "quia et suscipit\nsuscipit recusandae"
},
{
"userId": 1,
"id": 2,
"title": "qui est esse",
"body": "est rerum tempore vitae\nsequi "
},
{
"userId": 1,
"id": 3,
"title": "ea molestias quasi",
"body": "et iusto sed quo iure\nvoluptatem occaecati"
},
{
"userId": 1,
"id": 4,
"title": "qui est esse",
"body": "est rerum tempore vitae\nsequi "
},
]
//////////
list1=[
{
"userId": 1,
"id": 4,
"title": "qui est esse",
"body": "est rerum tempore vitae\nsequi "
},
]
thank u
Ok 👍 this code working for me:
Future<String> _loadTestDataAssetsCloud() async {
return await rootBundle.loadString('assets/testDataCloud.json');
}
Future<String> _loadTestDataAssetsUrl() async {
return await rootBundle.loadString('assets/testDataUrl.json');
}
Future testData() async {
var jsonUrl = await _loadTestDataAssetsUrl();
Map decodedUrl = jsonDecode(jsonUrl);
List<dynamic> individualsUrl = (((decodedUrl['CONSOLIDATED_LIST']
as Map)['INDIVIDUALS'] as Map)['INDIVIDUAL']);
var jsonCloud = await _loadTestDataAssetsCloud();
Map decodedCloud = jsonDecode(jsonCloud);
List<dynamic> individualsCloud = (((decodedCloud['CONSOLIDATED_LIST']
as Map)['INDIVIDUALS'] as Map)['INDIVIDUAL']);
List<dynamic> newList = [];
List<dynamic> delList = [];
individualsUrl.forEach((itemUrl) {
bool a = true;
individualsCloud.forEach((itemCloud) {
if (itemUrl['REFERENCE_NUMBER'] == itemCloud['REFERENCE_NUMBER']) {
a = false;
}
});
if (a == true) {
newList.add(itemUrl);
}
});
print('newList');
// print(newList);
print(newList.length);
newList.forEach((f){
print(f['REFERENCE_NUMBER']);
});
individualsCloud.forEach((itemCloud) {
bool d = true;
individualsUrl.forEach((itemUrl) {
if (itemCloud['REFERENCE_NUMBER'] == itemUrl['REFERENCE_NUMBER']) {
d = false;
}
});
if (d == true) {
delList.add(itemCloud);
}
});
print('delList');
// print(delList);
print(delList.length);
delList.forEach((f){
print(f['REFERENCE_NUMBER']);
});
}

Retrieving a specific JSON array from a JSON array of values

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>

How can I return a range of keys from a json object?

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));