Use Linq to get the last array from a Json response - json

I have a Json response which contains multiple arrays from which I need to get the last array. I want to select ExpenseDescriptions and return just this to the ajax call using Linq. ExpenseDescription is always the last array returned. The structure of my response is as follows:
{
"Data": {
"Items": [
{
"Result": {
"Id": "Some Data"
}
},
{
"Result": {
"Id": "Some More Data"
}
},
{
"Result": {
"ExpenseDescriptions": [
{
"Code": "TRH8",
"Description": "Some Description",
"UnitCost": 0,
"MaxThreshold": 0,
"MinThreshold": 0
},
{
"Code": "VVFT3",
"Description": "Some Description",
"UnitCost": 0,
"MaxThreshold": 0,
"MinThreshold": 0
}
]
}
}
]
}
}
I can use linq to do some basic clauses but can't figure out or find a way that lets me do the above. Any help in doing this with Linq would be appreciated.

Here's a solution using Newtonsoft.Json.Linq:
using System;
using System.Linq;
using System.Text;
using Newtonsoft.Json.Linq;
namespace test
{
class Program
{
static void Main(string[] args)
{
string json = #"{'Data': {
'Items': [
{
'Result': {
'Id': 'Some Data'
}
},
{
'Result': {
'Id': 'Some More Data'
}
},
{
'Result': {
'ExpenseDescriptions': [
{
'Code': 'TRH8',
'Description': 'Some Description',
'UnitCost': 0,
'MaxThreshold': 0,
'MinThreshold': 0
},
{
'Code': 'VVFT3',
'Description': 'Some Description',
'UnitCost': 0,
'MaxThreshold': 0,
'MinThreshold': 0
}
]
}
}
]
}
}";
JObject jsonobject = JObject.Parse(json);
var last_array = jsonobject.Descendants().Last(x => x.Type == JTokenType.Array);
foreach (var e in last_array)
{
Console.WriteLine(e.ToString());
}
}
}
}
output:
{
"Code": "TRH8",
"Description": "Some Description",
"UnitCost": 0,
"MaxThreshold": 0,
"MinThreshold": 0
}
{
"Code": "VVFT3",
"Description": "Some Description",
"UnitCost": 0,
"MaxThreshold": 0,
"MinThreshold": 0
}

Related

read json data from text file according to my conditions

here is my jason text file containing more than two json object having different policyNumber i want to read data on the base of policyNumber or may be another value and it show only those json object having same parameters that i request or say same policy number i sent to them.
I am working on API so i have no idea about this and i am also fresher in it field
no idea about how to return values.
plese guide and thanks in advance
my jason text file contain
{
"jsonData": {
"PolicyValue": {
"PolicyNumber": "003",
"EffectiveDate": "2022-09-14",
"MCV_NetBaseCashValue": 9700,
"Dividend": 0,
"DividendsInterest": 0,
"CouponBalance": 0,
"CouponBalancesInterest": 0,
"BaseCashValue": 700,
"CashSurrenderValue": 00,
"APLAmount": 0,
"APLAmountsInterest": 0,
"OPLAmount": 0,
"OPLAmountsInterest": 0,
"MiscellaneousSuspense": 0,
"PremiumSuspense": 0,
"OutstandingDisbursement": 0,
"SurrenderCharge": 0
}
},
"reponseCode": "00",
"reponseMessage": ""
}
{
"jsonData": {
"PolicyValue": {
"PolicyNumber": "123",
"EffectiveDate": "2022-08-17",
"MCV_NetBaseCashValue": -100,
"Dividend": 0,
"DividendsInterest": 0,
"CouponBalance": 0,
"CouponBalancesInterest": 0,
"BaseCashValue": 100,
"CashSurrenderValue": -100,
"APLAmount": 0,
"APLAmountsInterest": 0,
"OPLAmount": 0,
"OPLAmountsInterest": 0,
"MiscellaneousSuspense": 0,
"PremiumSuspense": 0,
"OutstandingDisbursement": 0,
"SurrenderCharge": 200
}
},
"reponseCode": "00",
"reponseMessage": ""
}
this is my first file
and my second file is
{
"jsonData": {
"PolicyNumber": "354",
"PolicyCommencementDate": "2020-07-31",
"InsuranceDetails": [ {
"PolicyNumber": "54",
"ClientID": "04",
"InsuredFirstName": "LEÄ",
"InsuredLastName": "HAÈNG",
"InsuredDOB": "1978-01-01"
},
{
"PolicyNumber": "54",
"ClientID": "09",
"InsuredFirstName": " YEÂN",
"InsuredLastName": "NG",
"InsuredDOB": "2006-11-08"
} ]
},
"reponseCode": "00", "reponseMessage": ""
}
{
"jsonData": {
"PolicyNumber": "737",
"PolicyCommencementDate": "2019-07-25",
"InsuranceDetails": [
{
"PolicyNumber": "37",
"ClientID": "15",
"InsuredFirstName": "N HAÛI",
"InsuredLastName": "ANH",
"InsuredDOB": "1989-10-04"
},
{
"PolicyNumber": "37",
"ClientID": "25",
"InsuredFirstName": "NH",
"InsuredLastName": "AÁN",
"InsuredDOB": "1988-01-04"
},
{
"PolicyNumber": "37",
"ClientID": "26",
"InsuredFirstName": "RUÙC",
"InsuredLastName": "DNG",
"InsuredDOB": "2021-05-17"
}
]
},
"reponseCode": "00",
"reponseMessage": ""
}
i want to apply on the base of get request please solve this issue as soon as possible
i teried this code in my value controller
public class ValuesController : ApiController
{
string[] fileConten = Directory.GetFiles(HostingEnvironment.MapPath(#"~/Documents/V1/policy/seachpolicy"));
public string Get()
{
string writeResult = string.Empty;
string strr = File.ReadAllText(fileConten[2]);
JObject jsonObj = (JObject)Newtonsoft.Json.JsonConvert.DeserializeObject(strr);
var jobj = JObject.Parse(jsonObj.ToString());
foreach (var item in jobj.Properties())
{
item.Value = item.Value["PolicyNumber"].ToString();
//item.Value = item.Value.SelectToken["PolicyValue"][0]["PolicyNumber"].ToString();
//item.Value = item.Value["PolicyNumber"][0]["InsuranceDetails"]["InsuredFirstName"].ToString();
int nm = Convert.ToInt32(item.Value);
if (nm == 008019354)
{
writeResult = jobj.ToString();
break;
}
break;
//item.Value = item.Value.ToString().Replace("0", "1");
}
return writeResult;
string output = Newtonsoft.Json.JsonConvert.SerializeObject(jsonObj, Newtonsoft.Json.Formatting.Indented);
return output;
this code not work properly
}

Access JSON values in a DRF API

How can I access "itemnumber" from this serializer?
Or how can I have a better serializer to access data in order_data[id][lot]['Qty'] format
{
"order_data": {
"id": [
{
"lot": {
"itemnumber": "sint ",
"Qty": 4
}
},
{
"lot": {
"itemnumber": "occa",
"Qty": 2
}
}
],
}
}
dt= AddItemsSerializer(data=request.data)
dt.is_valid(raise_exception=True)
order_data = dt.data.get('order_data')
Try this:
for id_dict in dt.data.get('order_data', {}).get('id', []):
print(id_dict.get('lot', {}).get('itemnumber'))
It will print out all values of itemnumber.

Parse JSON data with Axios and NodeJS Express (matching a schema for mongoose)

I am trying to parse JSON from an API, and because it has a randomly named property whose value is an object (of which has the data I need), I'm having trouble getting the data from it to match with a schema.
Here is a shortened API response just to show the problem I'm having.
{
"data": {
"1": {
"id": 1,
"name": "First Name",
"quotes": {
"USD": {
"price": 100
}
}
},
"1027": {
"id": 1027,
"name": "Second Name",
"quotes": {
"USD": {
"price": 200
}
}
}
}
}
And a shortened schema:
var coin = new Mongoose.Schema({
id: Number,
name: String,
quotes: {
USD: {
price: Number
}
}
});
So the question is, how would I grab "1"'s object and "1027"'s object without explicitly naming them. And is my schema syntax correct for the objects in question?
Thanks!
You can always use the for...in loop to check whether this data is what you have looking for
const response = {
"data": {
"1": {
"id": 1,
"name": "First Name",
"quotes": {
"USD": {
"price": 100
}
}
},
"1027": {
"id": 1027,
"name": "Second Name",
"quotes": {
"USD": {
"price": 200
}
}
}
}
}
for (let key in response.data) {
if (key === '1') {
console.log('Hey, I find it')
}
console.log(key)
}

How to get key from Observable?

I am trying to read data from firebase using angular 2 and typescript
my code
export class DashboardComponent implements OnInit {
itemsRef: AngularFireList<any>;
items: Observable<any[]>;
constructor( afDatabase: AngularFireDatabase) {
this.itemsRef = afDatabase.list('/user_orders/louro');
this.items = this.itemsRef.valueChanges();
this.items.subscribe(val_2 => {
alert(val_2.keys());
val_2.forEach(function (value2) {
{
Object.keys(value2).forEach(function(k2) {
{
// k is key
let count = Object.keys( (value2[k2] )).length;
console.log("New order key "+k2);
for(let i=0;i<count;i++){
console.log(i+"=> "+JSON.stringify (value2[k2][i]));
}
}
});
}
})
});
}
ngOnInit() {
}
}
and on val_2 only contains
[
{
"-L7rtl2NesdOYVD4-bMs": [
{
"ads_show": false,
"brand": "",
"buttonLabel": "Add to cart",
"child": "fruits",
"decrn": "testing for demonstrate",
"key": "-L7rtXc0pMQhi1ClK-pP",
"mid": "fresh fruits",
"note": "",
"orderInfo": {
"message": "nil",
"methode": "cash on delivery",
"status": "nil",
"time": 1521356314040,
"time2": 1521356254115
},
"p_id": 73,
"p_name": "testing",
"position": 0,
"primary_key": "testinglouro",
"qty": {
"m_qty": 1,
"qty": 23,
"unite": "1kg",
"user_intput_qty": 2
},
"quantity_new": 2,
"querykey_shop_name_top": "louro_fruits",
"sellerName": "louro",
"sellonline": true,
"seo": {
"meta_descrption": "",
"meta_title": ""
},
"service": false,
"serviceMessage": "Please enter your complaint details",
"serviceTitle": "Service Requesting",
"shopname": "louro",
"shopview": false,
"summery": "nil",
"tags": "",
"top": "fruits",
"uid": "IG2SxH6Gcabr3QVLz9jE9Wwweh62",
"variants": [
{
"img_position": 0,
"prize": {
"mrp": 58,
"selling_prize": 45,
"tax": 0
},
"qty": {
"m_qty": 1,
"qty": 23,
"unite": "1kg",
"user_intput_qty": 2
},
"shipping": {
"minmumbuy": 0,
"s_cost": 0,
"s_dlts": ""
}
}
],
"variants_position": 0
}
]
}
]
And my database is
I need this key "4X2NpohlbUa3AA7ri6iHGNm2If93" .How to get that key ? I tried val_2.key
but it showing error "[ts] Property 'key' does not exist on type 'any[]'. Did you mean 'keys'?"
In java i am using below code and work fine dataSnapshot1.getKey();
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference(getResources().getString(R.string.user_orders)+"/"+
shop_name,getContext()));
myRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
// This method is called once with the initial value and again
// whenever data at this location is updated.
// MainAction.setDefaults("OpenCategories",dataSnapshot.toString(),getActivity());
if (dataSnapshot.hasChildren()) {
for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) {
orderDetails1 = null;
orderDetails1 = new OrderDetails();
if (dataSnapshot1.hasChildren()) {
int id = -1;
for (DataSnapshot dataSnapshot2 : dataSnapshot1.getChildren()) {
id = id + 1;
if (dataSnapshot2.hasChildren()) {
int productid = -1;
for (DataSnapshot dataSnapshot3 : dataSnapshot2.getChildren()) {
productid = productid + 1;
if (dataSnapshot3.hasChildren()) {
orderDetails1.productmillaList.add(dataSnapshot3.getValue(Productmilla.class));
}
orderDetails1.productmillaList.get(productid).setPosition(Integer.parseInt(dataSnapshot3.getKey()));
orderDetails1.productmillaList.get(productid).setId(dataSnapshot2.getKey());
// Log.d("key2",dataSnapshot2.getKey()+" "+productid);
}
}
//orderDetails1.productmillaList.get(id).setId(dataSnapshot2.getKey());
}
}
orderDetails1.key = dataSnapshot1.getKey();
orderDetails.add(orderDetails1);
}
getaddress(orderDetails);
} else mProgressBar.setVisibility(View.GONE);
}
#Override
public void onCancelled(DatabaseError error) {
// Failed to read value
mProgressBar.setVisibility(View.GONE);
Log.w("dd", "Failed to read value."+ error.getMessage());
}
});
Update :
According to the updated response data, you should access using Object.keys(val)[0] which gives the value for key "4X2NpohlbUa3AA7ri6iHGNm2If93", since it is the first key.
According to older response data :
Your val is an array.
This should work.
Object.keys(val[0]).forEach(function(k1) {
{
console.log("Key first : "+ k1);
});
In your JSON, val is an array.
Object.keys(val[0])
will give you the keys of the first element of that array, which is what you're after.
TO get the first key in the Object
Object.keys(val)[0]; //returns 'first key'
[https://stackoverflow.com/a/11509718/7458082][1]
To iterate through the object
Object.keys(obj).forEach(function(key,index) {
// key: the name of the object key
// index: the ordinal position of the key within the object
});
[https://stackoverflow.com/a/11509718/7458082][1]

How to access Dynamodb's original JSON elements?

I am trying to test my lambda manually with the following dynamodb event input configured in tests -
Let's call this Json-1
{
"Records": [
{
"eventID": "1",
"eventVersion": "1.0",
"dynamodb": {
"Keys": {
"Id": {
"N": "101"
}
},
"NewImage": {
"Message": {
"S": "New item!"
},
"Id": {
"N": "101"
}
},
"StreamViewType": "NEW_AND_OLD_IMAGES",
"SequenceNumber": "111",
"SizeBytes": 26
},
"awsRegion": "us-west-2",
"eventName": "INSERT",
"eventSourceARN": eventsourcearn,
"eventSource": "aws:dynamodb"
},
{
"eventID": "2",
"eventVersion": "1.0",
"dynamodb": {
"OldImage": {
"Message": {
"S": "New item!"
},
"Id": {
"N": "101"
}
},
"SequenceNumber": "222",
"Keys": {
"Id": {
"N": "101"
}
},
"SizeBytes": 59,
"NewImage": {
"Message": {
"S": "This item has changed"
},
"Id": {
"N": "101"
}
},
"StreamViewType": "NEW_AND_OLD_IMAGES"
},
"awsRegion": "us-west-2",
"eventName": "MODIFY",
"eventSourceARN": sourcearn,
"eventSource": "aws:dynamodb"
},
{
"eventID": "3",
"eventVersion": "1.0",
"dynamodb": {
"Keys": {
"Id": {
"N": "101"
}
},
"SizeBytes": 38,
"SequenceNumber": "333",
"OldImage": {
"Message": {
"S": "This item has changed"
},
"Id": {
"N": "101"
}
},
"StreamViewType": "NEW_AND_OLD_IMAGES"
},
"awsRegion": "us-west-2",
"eventName": "REMOVE",
"eventSourceARN": sourcearn,
"eventSource": "aws:dynamodb"
}
]
}
However, the json of dynamodb items look like this -
Let's call this Json-2
{
"id": {
"S": "RIGHT-aa465568-f4c8-4822-9c38-7563ae0cd37b-1131286033464633.jpg"
},
"lines": {
"L": [
{
"M": {
"points": {
"L": [
{
"L": [
{
"N": "0"
},
{
"N": "874.5625"
}
]
},
{
"L": [
{
"N": "1765.320601851852"
},
{
"N": "809.7800925925926"
}
]
},
{
"L": [
{
"N": "3264"
},
{
"N": "740.3703703703704"
}
]
}
]
},
"type": {
"S": "guard"
}
}
}
]
},
"modified": {
"N": "1483483932472"
},
"qastatus": {
"S": "reviewed"
}
}
Using the lambda function below, I can connect to my table. My goal is create a json which elastic search will accept.
#Override
public Object handleRequest(DynamodbEvent dynamodbEvent, Context context) {
List<DynamodbEvent.DynamodbStreamRecord> dynamodbStreamRecordlist = dynamodbEvent.getRecords();
DynamoDB dynamoDB = new DynamoDB(new AmazonDynamoDBClient());
log.info("Whole event - "+dynamodbEvent.toString());
dynamodbStreamRecordlist.stream().forEach(dynamodbStreamRecord -> {
if(dynamodbStreamRecord.getEventSource().equalsIgnoreCase("aws:dynamodb")){
log.info("one record - "+dynamodbStreamRecord.getDynamodb().toString());
log.info(" getting N from new image "+dynamodbStreamRecord.getDynamodb().getNewImage().toString());
String tableName = getTableNameFromARN(dynamodbStreamRecord.getEventSourceARN());
log.info("Table name :"+tableName);
Map<String, AttributeValue> keys = dynamodbStreamRecord.getDynamodb().getKeys();
log.info(keys.toString());
AttributeValue attributeValue = keys.get("Id");
log.info("Value of N: "+attributeValue.getN());
Table table = dynamoDB.getTable(tableName);
}
});
return dynamodbEvent;
}
The format of a JSON item that elastic search expects is this and this is what I want to map the test input json to-
Let's call this Json-3
{
_index: "bar-guard",
_type: "bar-guard_type",
_id: "LEFT-b1939610-442f-4d8d-9991-3ca54685b206-1147042497459511.jpg",
_score: 1,
_source: {
#SequenceNumber: "4901800000000019495704485",
#timestamp: "2017-01-04T02:24:20.560358",
lines: [{
points: [[0,
1222.7129629629628],
[2242.8252314814818,
1254.702546296296],
[4000.0000000000005,
1276.028935185185]],
type: "barr"
}],
modified: 1483483934697,
qastatus: "reviewed",
id: "LEFT-b1939610-442f-4d8d-9991-3ca54685b206-1147042497459511.jpg"
}
},
So what I need is read Json-1 and map it to Json-3.
However, Json-1 does not seem to be complete i.e. it does not have information that a dynamodb json has - like points and lines in Json-2.
And so, I was trying to get a connection to the original table and then read this additional information of lines and points by using the ID.
I am not sure if this is the right approach. Basically, want to figure out a way to get the actual JSON that dynamodb has and not the one that has attribute types
How can I get lines and points from json-2 using java? I know we have DocumentClient in javascript but I am looking for something in java.
Also, came across a converter here but doesn't help me- https://github.com/aws/aws-sdk-js/blob/master/lib/dynamodb/converter.js
Is this something that I should use DynamoDBMapper or ScanJavaDocumentAPI for ?
http://docs.aws.amazon.com/AWSJavaSDK/latest/javadoc/com/amazonaws/services/dynamodbv2/datamodeling/DynamoDBMapper.html#marshallIntoObjects-java.lang.Class-java.util.List-com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapperConfig-
If yes, I am a little lost how to do that in the code below -
ScanRequest scanRequest = new ScanRequest().withTableName(tableName);
ScanResult result = dynamoDBClient.scan(scanRequest);
for(Map<String, AttributeValue> item : result.getItems()){
AttributeValue value = item.get("lines");
if(value != null){
List<AttributeValue> values = value.getL();
for(AttributeValue value2 : values){
//what next?
}
}
}
Ok, this seems to work for me.
ScanRequest scanRequest = new ScanRequest().withTableName(tableName);
ScanResult result = dynamoDBClient.scan(scanRequest);
for(Map<String, AttributeValue> item : result.getItems()){
AttributeValue value = item.get("lines");
if(value != null){
List<AttributeValue> values = value.getL();
for(AttributeValue value2 : values){
if(value2.getM() != null)
{
Map<String, AttributeValue> map = value2.getM();
AttributeValue points = map.get("points");
List<AttributeValue> pointsvalues = points.getL();
if(!pointsvalues.isEmpty()){
for(AttributeValue valueOfPoint : pointsvalues){
List<AttributeValue> pointList = valueOfPoint.getL();
for(AttributeValue valueOfPoint2 : pointList){
}
}
}
}
}
}
}