I have the following JSON:
{
"result": "success",
"json": {
"'1'-'V17511500523287'": [{
"hits": 1,
"sid": 1,
}]
}
}
I would like to turn it into:
{
"result": "success",
"json": [{
"hits": 1,
"sid": 1,
}],
"length": 1
}
Meaning id like to remove "'1'-'V17511500523287'" but keep the inner content.
Is this somehow possible?
You can use Object.keys(...) to get the keys in your result and then use it to get the inner content like you want.
Here is some code to achieve that. Put it in a function if you plan to do that elsewhere.
var response = {
"result": "success",
"json": {
"'1'-'V17511500523287'": [{
"hits": 1,
"sid": 1,
}]
}
};
var response_keys = Object.keys(response.json);
response.length = response_keys.length;
if (response_keys.length == 1) {
response.json = response.json[response_keys[0]];
} else {
// you can drop that if you don't want to handle more than one key,
// or throw/return an error instead
var _tmp = [];
response_keys.forEach(function(key) {
_tmp.push(response.json[key]);
});
response.json = _tmp;
_tmp = undefined;
}
console.log(JSON.stringify(response, null, 2));
Output:
{
"result": "success",
"json": [
{
"hits": 1,
"sid": 1
}
],
"length": 1
}
Related
I am trying to access the name object in this Json to put in a local variable in a Postman Test.
Json
{
"Line": [
{
"Id": "1",
"LineNum": 1,
"Description": "Custom Design",
"Amount": 75.00,
"DetailType": "SalesItemLineDetail",
"SalesItemLineDetail": {
"ItemRef": {
"value": "4",
"name": "Design"
},
"UnitPrice": 75,
"Qty": 1,
"ItemAccountRef": {
"value": "82",
"name": "Design income"
},
"TaxCodeRef": {
"value": "NON"
}
}
}
]
}
I am using this code to loop through the Line Array but if I try and go deeper than 1 level Itemref it returns undefined
let ProductArray=[];
for (let i=0; i < Line.length; i++) {
//
ProductArray.push({
"value":Line[i].SalesItemLineDetail.ItemRef.name
})
}
I have also tried
'"value":Line[i].SalesItemLineDetail["ItemRef"].name
"value":Line[i].SalesItemLineDetail["ItemRef"]["name"]
all return ItemRef undefined
What is the correct syntax or code?
TIA
There are just some small pieces missing with your code. I re-create a test and mocked the same JSON data. I just add the missing pieces to your code and the test was Successful.
GET Request:
//Response body JSON
{
"Line": [
{
"Id": "1",
"LineNum": 1,
"Description": "Custom Design",
"Amount": 75,
"DetailType": "SalesItemLineDetail",
"SalesItemLineDetail": {
"ItemRef": {
"value": "4",
"name": "Design"
},
"UnitPrice": 75,
"Qty": 1,
"ItemAccountRef": {
"value": "82",
"name": "Design income"
},
"TaxCodeRef": {
"value": "NON"
}
}
}
]
}
// Tests
// Check response body
const res = pm.response.json().Line;
let ProductArray=[];
for (let i=0; i < res.length; i++) {
const res = pm.response.json().Line;
ProductArray.push({
"value":res[i].SalesItemLineDetail.ItemRef.name
})
// Lets see console.log result
console.log('Check For:', res[i].SalesItemLineDetail.ItemRef.name)
// Set Result to environment variables
pm.environment.set("variable_key", res[i].SalesItemLineDetail.ItemRef.name);
}
console.log output: Design which is also added to environment variables.
I want to edit this json file:
{
"shipping_orders": [{
}],
"timestamp": 100,
"shoporders": [{
"buyer_remark": null
}],
"payment_channel_info": {
"shipping_method": 28,
"grouping_info": {
"groups": [{
"display_info": {
"discount": 1
}
}]
}
}
}
And I want to add these json objects to the file:
"headers": {}
"ext_ad_info_mappings": []
"enabled": true
The output I want is like this:
{
"headers": {},
"shipping_orders": [{
}],
"timestamp": 100,
"shoporders": [{
"buyer_remark": null,
"ext_ad_info_mappings": []
}],
"payment_channel_info": {
"shipping_method": 28,
"grouping_info": {
"groups": [{
"display_info": {
"discount": 1,
"enabled": true
}
}]
}
}
}
I tried this command but the result only shows true https://jqplay.org/s/0aVbFzMttK
jq '.+{"headers": {}} and .shoporders[] + {"ext_ad_info_mappings": []} and .payment_channel_info.grouping_info.groups[].display_info + {"enabled": true}'
How should I edit the json file so that it'll output like the one I want above ?
Just locate where in the tree you want to set the values and set them.
.headers = {}
| .shoporders[].ext_ad_info_mappings = []
| .payment_channel_info.grouping_info.groups[].display_info.enabled = true
https://jqplay.org/s/ugF5foO90N
{
"id": "aghysfgagaw365",
"MetricLevelId": "4890718305",
"level": "BUB",
"type": "Mash",
"summary": {
"counts": [
{},
{
"label": {},
"value": 2674,
"labelLoc": {
"192706": {
"ADD": 8977,
"DEL": 3257,
"Count": 59
},
"543419": {
"ADD": 0,
"DEL": 0,
"Count": 1
}
}
}
]
}
}
I read the documentation but i'm still unclear to validate a complex API's like this. a demo to validate this API would help me to solve other API validations...especially this one has a dynamic JSON key.how do i validate ADD,DEL and Cont with "192706" being dynamic.
From the docs, please refer to the documentation on JsonPath. Also recommended is the section on "JSON Transforms". Here is one way:
* def response =
"""
{
"id": "aghysfgagaw365",
"MetricLevelId": "4890718305",
"level": "BUB",
"type": "Mash",
"summary": {
"counts": [
{
},
{
"value": 2674,
"labelLoc": {
"192706": {
"ADD": 8977,
"DEL": 3257,
"Count": 59
},
"543419": {
"ADD": 0,
"DEL": 0,
"Count": 1
}
}
}
]
}
}
"""
* def label = get[0] response..labelLoc
* def vals = get label.*
* match each vals == { ADD: '#number', DEL: '#number', Count: '#number' }
EDIT also this would work:
* json keys = label.keySet()
* match keys == ['192706', '543419']
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){
}
}
}
}
}
}
}
I am trying to figure out how to output a structured JSON from a query to my API. I have the following 2 tables (MySQL):
**TABLE1:**
uid
name
pptw
**TABLE2**
id
table1_uid
assignment
start_time
end_time
date
comments
And this is the JSON output I am looking for:
$scope.table1 = {
"toplevel":
[
{
"uid": 1,
"name": "john",
"pptw": "ATWF",
"child":
{
"id": 1,
"table1_uid": 1,
"assignment": null,
"start_time": "14:53:00",
"end_time": "15:00:00",
"date": null,
"comments": null
}
},
{
"uid": 22,
"name": "carol",
"pptw": "DWFF",
"child":
{
"id": 2,
"table1_uid": 22,
"assignment": null,
"start_time": "11:00:00",
"end_time": "14:00:00",
"date": null,
"comments": "Completed"
}
}
]
}
I have a promise as follow:
var request = $http({
method: 'post',
url: '.../api/v1/ppp',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
params: {
//record_uid: record_uid,
}
})
.success(function (data, status, headers, config) {
deferred.resolve(data);
})
.error(function (data, status) {
deferred.reject();
});
return deferred.promise;
And on the database, I have the following query:
SELECT tb1.uid
tb1.name
tb1.pptw,
tb2.id,
tb2.table1_uid,
tb2.assignment,
tb2.start_time,
tb2.end_time,
tb2.date,
tb2.comments
FROM
table1 tb1, table2 tb2
WHERE
tb1.uid = tb2.table1_uid
I would appreciate any ideas on how to achieve this, thanks a lot.
This is the solution to my questions, I managed to figure out how to do it. I hope it helps someone else trying to do the same thing as I did.
Here is how to create the hierarchical JSON:
var results_tree_header = [];
var results_tree = [];
if (result.rows.length > 0) {
for (var i = 0; i < result.rows.length; i++) {
results_tree.push({
"uid": result.rows.item(i).uid,
"name": result.rows.item(i).name,
"pptw": result.rows.item(i).pptw,
"child":
{
"id": result.rows.item(i).id,
"table1_uid": result.rows.item(i).table1_uid,
"assignment": result.rows.item(i).assignment,
"start_time": result.rows.item(i).start_time,
"end_time": result.rows.item(i).end_time,
"date": result.rows.item(i).date,
"comments": result.rows.item(i).comments
}
});
results_tree_header = { toplevel: results_tree };
}
}