How would you reduce a json value - json

I have a Graphql returning values that look like this
"{\"date\":\"2020-05-21\",\"time\":null,\"changed_at\":\"2020-05-25T16:16:33.201Z\"}"
How would you target just the date to return "2020-05-21"?
Here is a larger picture of the retuned.
"column_values": [
{
"value": null,
"id": "check8",
"title": "Approved?"
},
{
"value": "{\"date\":\"2020-05-21\",\"time\":null,\"changed_at\":\"2020-05-25T16:16:33.201Z\"}",
"id": "due_date2",
"title": "Due Date"
},
{
"value": null,
"id": "qtr",
"title": "QTR"
},
{
"value": null,
"id": "status5",
"title": "Priority"
},
{
"value": "{\"index\":2,\"post_id\":null,\"changed_at\":\"2020-05-22T17:56:59.936Z\"}",
"id": "status",
"title": "Status"
},
{
"value": null,
"id": "progress",
"title": "Progress"
},
{
"value": null,
"id": "link",
"title": "Video Link"
},
{
"value": null,
"id": "formula8",
"title": "DATE_API"
}
]
}
Do you have to parse the JSON or Stringify it first? perhaps Graphql isn't returning usable json. Thank you for any help or bump in the correct direction.

JSON.stringify() is the method used to generate a JSON string. If you apply it to something that's already a JSON string then you'll get a double-encoded JSON string.
What you need to use is the JSON.parse() method:
const jsonObject= '{"foo": "bar"}';
const decoded = JSON.parse(jsonObject);
console.log(decode, typeof decoded);
Result:
{ foo: 'bar' } 'object'

Related

Reformat JSON object using Dart

I need to standardize the object response key/values so that they are easier to parse/traverse using the tool I'm integrating.
Starting with the following JSON:
{
"status": true,
"body": {
"phone": "+1 937-830-1167",
"address": "2323 kuhku",
"linkedin": "uhku",
"twitter": "uhukh",
"education": "weeww",
"work_experience": "wewaew",
"write_something_about_you": "yugtyt",
"why_you_think_you_are_good_for_this_job": "kuhhuk",
"write_your_assignment_question": "kuhghuhghj",
"upload_your_attachment": null,
"upload_your_resume_here": null
}
}
Using Dart, what would be the best way to reformat as shown?
{
"status": true,
"body": {
"answers":[
{
"label": "phone",
"answer":"+1 937-830-1167"
},
{
"label": "address",
"answer":"2323 kuhku"
},
{
"label": "linkedin",
"answer": "uhku"
},
{
"label": "twitter",
"answer": "uhku"
},
{
"label": "education",
"answer": "uhku"
},
{
"label": "work_experience",
"answer": "uhku"
},
{
"label": "write_something_about_you",
"answer": "uhku"
},
{
"label": "why_you_think_you_are_good_for_this_job",
"answer": "uhku"
},
{
"label": "write_your_assignment_question",
"answer": "uhku"
},
{
"label": "upload_your_attachment",
"answer": "uhku"
},
{
"label": "write_something_about_you",
"answer": "upload_your_resume_here"
}
]
}
}
I'm somewhat limited by the tool I'm using so this will make it much easier to parse the JSON object with JSON Path as needed.
Looks like something that should be easily doable as:
var json = ... your json ...;
var result = {
"status": json["status"],
"body": [for (var e in json["body"].entries)
{"label": e.key, "answer": e.value}
]
};
Create a new JSON object with the same "status" and a "body" which is a list instead of a map, and for each entry in the original map, create a JSON object with a "label" and "answer" taken from the key and value of the map entry.

How to parameterize a part of string in a field of the response in karate

I am trying to print a response based on the particular parameters.
For that, I have the response from an API as below:
{
"ABC": {
"code": "ABC",
"isActive": "true",
"lastUpdatedBy": "username",
"execution": {
"status": "0",
},
"priority": "1"
},
"DEF": {
"code": "DEF",
"isActive": "true",
"lastUpdatedBy": "username",
"execution": {
"status": "1",
},
"priority": "1"
},
"GHI": {
"code": "GHI",
"isActive": "true",
"lastUpdatedBy": "username",
"execution": {
"status": "2",
},
"priority": "1"
},
"JKL": {
"code": "JKL",
"isActive": "true",
"lastUpdatedBy": "username",
"execution": {
"status": "0",
},
"priority": "1"
},
}
Here is the feature file that I am using to print that particular value:
Feature: Value extraction
Background:
* def all = [ABC,DEF,GHI,JKL]
Scenario: Extract response value
Given url
When method get
Then status 200
And def value = []
And eval for(var i=0;i<all.length;i++) {value.add(response['#(all[i])']["execution"]["status"]) }
And print value
I want to extract the value of all parameters whose status is "0".
print response["ABC"]["execution"]["status"]
The above line gives the result but I want to parameterise the ["ABC"] part
Any help on this? Is there any other way I can achieve this or am I doing something wrong to achieve this particular edge case?
I'm providing a sample below that answers multiple questions:
* def response =
"""
{
"ABC": {
"code": "ABC",
"isActive": "true",
"lastUpdatedBy": "username",
"execution": {
"status": "0",
},
"priority": "1"
},
"DEF": {
"code": "DEF",
"isActive": "true",
"lastUpdatedBy": "username",
"execution": {
"status": "1",
},
"priority": "1"
}
}
"""
# get all values in root json
* def items = $.*
* def code = 'ABC'
* def found = items.filter(x => x.code == code && x.execution.status == '0')
* assert found.length == 1
# the expression on the right below is pure JS
* match found[0] == response[code]
Note:
how to use json-path to simplify JSON, also refer: https://stackoverflow.com/a/68811696/143475
how to use the filter() API to "find" data using complex expressions, that can be parameterized, also see: https://github.com/karatelabs/karate#json-transforms
how to get the value of a key that can be dynamic and parameterized

avro runtime exception not a map when return in Json format

i have a avro schema for UKRecord, which contain a list of CMRecord(also avro schemaed):
{
"namespace": "com.uhdyi.hi.avro",
"type": "record",
"name": "UKRecord",
"fields": [
{
"name": "coupon",
"type": [
"null",
"string"
],
"default": null
},
{
"name": "cm",
"type": [
"null",
{
"type": "array",
"items": {
"type": "record",
"name": "CmRecord",
"fields": [
{
"name": "id",
"type": "string",
"default": ""
},
{
"name": "name",
"type": "string",
"default": ""
}
]
}
}
],
"default": null
}
]
}
in my java code, i create a UKRecord which has all fields populated correctly, eventually i need to return this object using a json based api, however it complained:
org.apache.avro.AvroRuntimeException: Not a map: {"type":"record","name":"CmRecord","namespace":"com.uhdyi.hi.avro","fields":[{"name":"id","type":"string","default":""},{"name":"name","type":"string","default":""}]}
the java code that write the object to json is :
ObjectWriter writer = ObjectMapper.writer();
if (obj != null) {
response.setHeader(HttpHeaders.Names.CONTENT_TYPE, "application/json; charset=UTF-8");
byte[] bytes = writer.writeValueAsBytes(obj); <-- failed here
...
}
obj is:
{"coupon": "c12345", "cm": [{"id": "1", "name": "name1"}, {"id": "2", "name": "name2"}]}
why do i get this error? please help!
Because you are using unions, Avro is uncertain how to interpret the JSON you are providing. Here's how you can change the JSON so Avro knows it's not null
{
"coupon": { "string": "c12345" },
"cm": { "array": [
{ "id": "1", "name": "name1" },
{ "id": "2", "name": "name2" }
]
}
}
I know, it's really annoying how Avro chose to handle nulls.

BackboneJs understandable Json Format for Json Parse

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

Linq to Json using Like Clause

I've got an MVC 3 web app and am returning a JSON object which I would like to use Linq against to limit the result returned to the client jquery.
The Json response takes the following structure:
{
"Data": {
"Items": [
{
"Result": {
"Id": "e2ba4912-c387-4f54-b55e-06742a6858db",
"Name": "SomeOtherSetting",
"Value": "500",
"Archived": false
},
"Result": {
"Id": "17c27584-cea8-42c2-b6c4-0b30625ac3ce",
"Name": "Setting2",
"Value": "600",
"Archived": false
},
"Result": {
"Id": "17c27584-cea8-42c2-b6c4-0b30625ac3ce",
"Name": "Setting3",
"Value": "700",
"Archived": false
}
}]
}
}
....
I need to return or grab just the json items that have a Name like 'Setting' for example. In the example, this would return just the 2 Json nodes.
My Linq is very limited and what I have is: Settings is where the Json response is stored.
NewtonSoft.Json.Linq.JObject data = NewtonSoft.Json.Linq.JObject.Parse(Settings);
var result = from p in data["Data"]["Items"].Children()
where (p["Result"]["Name"].Contains("Expenses.Help.Tip"))
select new { Name = (string)p["Result"]["Name"], Value = (string)p["Result"]["Value"] };
When I run this I get nothing in my result. Can anyone help and tell me what I'm doing wrong?
Thanks.
Well, I'm not a Json specialist, but I think your Json structure has some problems.
I tried an online parser, and parsing took only the third result... (try to copy past your code in the left window, and look at JS eval.
Instead of
"Items": [
{
"Result": {
},
"Result": {
},
"Result": {
}
}]
you should have each element of Items array (each 'Result') into {}.
"Items": [
{
{"Result": {
}
},
{"Result": {
}
},
{"Result": {
}
}]
I got it to work by changing your Json file to
{
"Data": {
"Items": [
{
"Result": {
"Id": "e2ba4912-c387-4f54-b55e-06742a6858db",
"Name": "SomeOtherSetting",
"Value": "500",
"Archived": false
}
},
{
"Result": {
"Id": "17c27584-cea8-42c2-b6c4-0b30625ac3ce",
"Name": "Setting2",
"Value": "600",
"Archived": false
}
},
{
"Result": {
"Id": "17c27584-cea8-42c2-b6c4-0b30625ac3ce",
"Name": "Setting3",
"Value": "700",
"Archived": false
}
}]
}
}
using
var data = JObject.Parse(test)["Data"]["Items"].Children()
.Where(m => m["Result"]["Name"].Value<string>().Contains("Setting"))
.Select(m => new
{
Name = m["Result"]["Name"].Value<string>(),
Value = m["Result"]["Value"].Value<int>()
})
.ToList();