I'm having this response
"countryitems": [
{
"1": {
"ourid": 1,
"title": "Afghanistan",
"code": "AF",
},
"2": {
"ourid": 2,
"title": "Albania",
"code": "AL",
},
"3": {
"ourid": 3,
"title": "Algeria",
"code": "DZ", },
"4": {
"ourid": 4,
"title": "Angola",
"code": "AO",
}
}
]
For question, I've put only 4 nodes where actually I've 150 around of nodes. I'm not getting how can I parse to get country names?
Here is a possible solution. You have to decode the response with jsonDecode and generating a map out of the response. If you iterate through the map, you can access the inner nodes.
import 'dart:convert';
var jsonString =
"""
{
"countryitems": [
{
"1": {
"ourid": 1,
"title": "Afghanistan",
"code": "AF"
},
"2": {
"ourid": 2,
"title": "Albania",
"code": "AL"
},
"3": {
"ourid": 3,
"title": "Algeria",
"code": "DZ"
},
"4": {
"ourid": 4,
"title": "Angola",
"code": "AO"
}
}
]
}
""";
void main() {
Map<String, dynamic> obj = json.decode(jsonString)['countryitems'][0];
// print out all country names in obj
for(int i = 1; i <= obj.length; i++) {
print(obj['$i']['title']);
}
}
'dart:convert' is good for simple cases.
But when you need true flexibility and less boilerplate, I'd suggest to use this library instead https://github.com/k-paxian/dart-json-mapper
Related
I am trying to pull the type JSON data from "0", but I'm getting a SyntaxError. In postman, part of the returned data looks like this:
var array = {
"catalogs": {
"add": {
"0": {
"type": 'catalog',
"id": '2027528',
"date_create": '1637310194',
"date_modify": '1637310194',
"created_by": '7382229',
"modified_by": '7382229',
"catalog_id": '8241',
"name": '',
"deleted": '0',
"custom_fields": {
"0": {
"id": '912743',
"name": 'Статус',
"values": {
"0": {
"value": 'Создан',
"enum": '4197277'
}
},
"code": 'BILL_STATUS'
},
"1": {
"id": '912747',
"name": 'Плательщик',
"values": {
"0": {
"value": {
"name": 'TEST+TEST',
"entity_id": '63836888',
"entity_type": 'contacts'
}
}
},
"code": 'PAYER'
},
"2": {
"id": '912753',
"name": 'Позиции+счета',
"values": {
"0": {
"value": {
"sku": '',
"description": '1111',
"unit_price": '1111',
"unit_type": 'шт',
"quantity": '1',
"discount": {
"type": 'amount',
"value": '0'
},
"vat_rate_id": '0',
"vat_rate_value": '20',
"bonus_points_per_purchase": '0',
"external_uid": ''
}
}
},
"code": 'ITEMS'
},
"3": {
"id": '912755',
"name": 'Комментарий',
"values": {
"0": {
"value": '1111'
}
},
"code": 'BILL_COMMENT'
},
"4": {
"id": '912757',
"name": 'Стоимость',
"values": {
"0": {
"value": '1111'
}
},
"code": 'BILL_PRICE'
}
},
"created_at": '1637310194',
"updated_at": '1637310194'
}
}
},
"account": {
"_links": {
"self": 'https://amocrm.ru'
},
"subdomain": 'mylogoped',
"id": '24809335'
}
};
When I try to use the code, I get an error (SyntaxError: Unexpected number)
var myDat = testOne.catalogs.add.0.type;
Found a solution in one of the posts, but it does not work, an error also comes out
for (let i = 0; i < testOne.catalogs.add.0.length; i++) {
var type = testOne.catalogs.add.0[i].type;
sheet.getRange(lastRow + 1, 5).setValue(type);
}
Found a solution here SyntaxError: Unexpected number when pulling JSON data but it doesn't work because SyntaxError: Unexpected token '['
for (let i = 0; i < testOne.catalogs.add.["0"].length; i++) {
var type = testOne.catalogs.add.["0"][i].type;
sheet.getRange(lastRow + 1, 5).setValue(type);
}
Please tell me how I can take data from the "0" array, everything behind it is pulled like this
var myData = testOne.account.subdomain;
You have no array in the JSON data.
It is an object with nested objects. Also the .["0"] syntax is incorrect.
You could do something like the following to iterate:
var keys = Object.keys(testOne.catalogs.add);//array of keys
for (let i = 0; i < keys.length; i++) {
var type = testOne.catalogs.add[keys[i]].type;
// ...do something
}
But it will not guarantee the order of items to be the same as you see in the data because of how the objects work. If order is important then you can sort the keys array accordingly.
Below is the JSON data retrieved successfully from the server in flutter application
{
"error": "false",
"notification": [
{
"rn": "1",
"id": "224",
"company_details": {
"code": "2",
}
},
{
"rn": "2",
"id": "219",
"company_details": {
"code": "3",
}
},
{
"rn": "3",
"id": "213",
"company_details": {
"code": "3",
}
},
{
"rn": "4",
"id": "209",
"company_details": {
"code": "4",
}
},
{
"rn": "5",
"id": "204",
"company_details": {
"code": "3",
}
},
{
"rn": "6",
"id": "199",
"company_details": {
"code": "3",
}
},
{
"rn": "7",
"id": "193",
"company_details": {
"code": "3",
}
}
],
}
The code used here is below
List notificationsList;
getnotifications(int page) async {
Map data = {
'user_id': “VICKY,
"page":page.toString()
};
var response = await http.post(companyorders, body: data);
if(response.statusCode == 200) {
jsonResponse = json.decode(response.body);
print('Response status: ${response.statusCode}');
print('Response body: ${response.body}');
String errorcheck = jsonResponse['error'];
companyDetail = NotificationModel.fromJson(json.decode(response.body));
companyDetail = NotificationModel.fromJson(json.decode(response.body));
print('names of companies');
print(companyDetail.content);
List list = jsonResponse['notification'];
notificationsList.add(list);
}
}
When I tried to add the list to the notificationsList I got the below error
Unhandled Exception: NoSuchMethodError: The method 'add' was called on
null. Receiver: null Tried calling: add(Instance(length:7) of
'_GrowableList')
#0 Object.noSuchMethod (dart:core-patch/object_patch.dart:51:5)
I want to add the data retrieved to the notificationsList, how should I do that
You need to initialize notificationsList:
List notificationsList = [];
Also since list is an iterable therefore use addAll()
I'm totally new to python. I want to merge two JSON files who have the same objects but different keys.
Here is a basic example of the result I would love to get :
JSON1 :
{
"json1" : {
"1" : {
"id": 1,
"name": "first_artist",
"imageUrl": "https://1.jpg",
"genre": "Rap "
},
"2" : {
"id": 2,
"name": "second_artist",
"imageUrl": "https://2.jpg",
"genre": "Hip-Hop"
}
}
}
JSON2:
{
"json2" : {
"1" : {
"date": 17/07/19,
"venue": "venue1"
},
"2" : {
"date": 19/07/19,
"venue": "venue2"
}
}
}
Expected JSON:
{
"expected_json" : {
"1" : {
"id": 1,
"name": "first_artist",
"imageUrl": "https://1.jpg",
"genre": "Rap "
"date": 17/07/19,
"venue": "venue1"
},
"2" : {
"id": 2,
"name": "second_artist",
"imageUrl": "https://2.jpg",
"genre": "Hip-Hop"
"date": 19/07/19,
"venue": "venue2"
}
}
}
Can someone give tips and direction to make this possible ? Thanks
You can simplify your input to:
A.json:
{
"1" : {
"id": 1,
"name": "first_artist",
"imageUrl": "https://1.jpg",
"genre": "Rap "
},
"2" : {
"id": 2,
"name": "second_artist",
"imageUrl": "https://2.jpg",
"genre": "Hip-Hop"
}
}
B.json:
{
"1" : {
"date": "17/07/19",
"venue": "venue1"
},
"2" : {
"date": "19/07/19",
"venue": "venue2"
}
}
and you have to change 19/07/19 to "19/07/19" for it to be valid json.
Now you can use the json module:
import json
#from pprint import pprint
# load json from files
with open('A.json') as A_file:
A = json.load(A_file) # returns a dict()
#print('A:')
#pprint(A)
with open('B.json') as B_file:
B = json.load(B_file)
#print('\nB:')
#pprint(A)
# get a list of unique keys -> {'1', '2'}
keys = set()
keys.update(A.keys())
keys.update(B.keys())
#print(f'\nkeys: {keys}')
# for each key merge values from dicts A and B
result = {}
for key in keys:
#print(f'\n{key}:')
merge = {}
if key in A:
merge.update(A[key])
if key in B:
merge.update(B[key])
#pprint(merge)
result[key] = merge
#print('\nresult:')
#pprint(result)
# write the result to expected.json
with open('expected.json', 'w+') as expected_file:
expected_file.write(json.dumps(result, sort_keys=True, indent='\t'))
This writes:
expected.json:
{
"1": {
"date": "17/07/19",
"genre": "Rap ",
"id": 1,
"imageUrl": "https://1.jpg",
"name": "first_artist",
"venue": "venue1"
},
"2": {
"date": "19/07/19",
"genre": "Hip-Hop",
"id": 2,
"imageUrl": "https://2.jpg",
"name": "second_artist",
"venue": "venue2"
}
}
I am trying to match the ids of two json files and return the matching objects. These are the 2 json files:
{
"een": {
"id": "100",
"title": "Entertainment and stuff"
},
"twee": {
"id": "107",
"title": "Sport for everyone"
},
"drie": {
"id": "108",
"title": "Eating is good"
}
}
This is the second one:
[
{
"name": "Entertainment",
"id": "100",
"price": 2600,
"gifted": false
},
{
"name": "Sport",
"id": "107",
"price": 2500,
"gifted": false
}
]
As a result of the 2 matching idvalues I should get:
[
{
"name": "Entertainment",
"id": "100",
"price": 2600,
"gifted": false,
"title": "Entertainment and stuff"
},
{
"name": "Sport",
"id": "107",
"price": 2500,
"gifted": false,
"title": "Sport for everyone"
}
]
I was wondering if there was a fancy way using lodash or something else and do this in a nice compact way?
One possible solution would be to use merge to merge two objects that have the id as the key. This can be done using keyBy on the array and also on the values of the first object. Intersection is used find ids that are in both arrays.
let list1 = {
"een": {
"id": "100",
"title": "Entertainment and stuff"
},
"twee": {
"id": "107",
"title": "Sport for everyone"
},
"drie": {
"id": "108",
"title": "Eating is good"
}
}
let list2 = [
{
"name": "Entertainment",
"id": "100",
"price": 2600,
"gifted": false
},
{
"name": "Sport",
"id": "107",
"price": 2500,
"gifted": false
}
]
let o1 = _.keyBy(_.values(list1), 'id');
let o2 = _.keyBy(list2, 'id');
let matchingIds = _.intersection(_.keys(o1), _.keys(o2));
let result = _.chain(o1)
.pick(matchingIds)
.merge(_.pick(o2,matchingIds))
.values()
.value()
Building on #GruffBunny's answer, you want to take his result and filter out those ids that aren't found in o1 and o2.
let o1 = _.keyBy(_.values(list1), 'id'));
let o2 = _.keyBy(list2, 'id');
let idsToPull = _.difference( _.map(o1, 'id'), _.map(o2, 'id')) //["108"]
let merged = _.values(_.merge(o1, o2 ));
let result = _.filter(merged, function(obj){ return _.indexOf(idsToPull, obj.id) === -1 })
I have two type of JSON format one is with a single data, another one is with multiple data in an array of JSON.
First JSON format:
{
"data": {
"id": "1",
"artist": "Gotye",
"title": "Making Mirrors"
}
}
Second:
{
"data": [
{
"id": "1",
"artist": "Gotye",
"title": "Making Mirrors"
},
{
"id": "99",
"artist": "uy",
"title": "uy"
},
{
"id": "100",
"artist": "yt",
"title": "yt"
},
{
"id": "101",
"artist": "65",
"title": "565"
},
{
"id": "102",
"artist": "6",
"title": "6"
},
{
"id": "103",
"artist": "y",
"title": "yy"
},
{
"id": "104",
"artist": "ty",
"title": "yt"
}
]
}
In backbone model when I do:
parse: function(response) {
return response.data;
}
for the first one, it works which i can populate the JSON data to the view, but for the second JSON it does not.
I am wondering if there is any way that could make the backbone parse function to standardize the JSON format to backbone understadable format. Any advice or any solution for this will be much appreciated. Thank you