Assign Data from child to parent in json object - json

I had a object array containing items
"0: Object
Entity: "Customer"
Id: 157
Message: "testMessage1"
Property: Object
Name: "LastName"
Rules: "NotEmpty""
Here, How could I pass Name value to Property
Name is act as key within in Property object.
how could I Discard the Name and assign the value of Name i.e. (Last Name) to Property
This is what I have right now:
[
{
"Entity":"Customer",
"Property": {"Name": "Email", "Type": "System.String" },
"Rules":"NotEmpty",
"Message":"ssdsdsds",
"Id":157,
"ValueToCompare": null,
}
]
Here, I need to assign Name value (i.e : Email) to Property Directly (it would be like this :-- "Property": "Email")

assuming this is your json
[
{
"0": {
"Entity": "Customer",
"Id": 157,
"Message": "testMessage1"
},
"Property": {
"Name": "LastName",
"Rules": "NotEmpty"
}
}
]
your original json contain in
originaljson
and transform json contain in
transformjson
JSONArray originaljson;
JSONArray transformjson=originaljson;
for(int i=0;i<originaljson.length();i++)
{
JSONObject mainJson=originaljson.getJSONObject(i);
String name=mainJson.getJSONObject("Property").getString("Name");
//mainJson.remove("Property");
JSONObject mainJsonTransform=transformjson.getJSONObject(i);
mainJsonTransform.remove("Property");
mainJsonTransform.put("Property",name);
}
now your transformjson contain the desired json

Thank you guys for your interest with this question.
At last I have write down the proper solution
My own solution to solve this problem is..
In javascript :
function addProp(obj, propName) {
for (var p in obj) {
if (obj.hasOwnProperty(p)) {
if (p == propName) {
if (obj[p].Name == null) {
obj[p] = obj[p];
}
else
{
obj[p] = obj[p].Name;
}
} else if (typeof obj[p] == 'object') {
addProp(obj[p], propName);
}
}
}
return obj;
}
Calling this function :
addProp(data, 'Property')
This work properly now

Related

Scala: Edit/Modify json string based on internal value

I have a json string structured similarly to the following:
val json : String =
{
"identifier":{
"id":"1234_567_910",
"timestamp":"12:34:56",
},
"information":[
{
"fieldName":"test_name",
"fieldId":"test_fieldId",
}
]
}
What I want to do is create a check that verifies the 'id' field matches the structure "Int_Int_Int" and if it doesn't I want to change the value to match this intended structure but I want to keep the rest of the information in the json string as is.
So if I received the following 'id' fields within a json string I would want to change them like so:
"id":"1234_567_910" -> do nothing
"id":"1234" -> "id":"1234_0_0"
"id":"1234_567" -> "id":"1234_567_0"
"id":"1234_???" -> "id":"1234_0_0"
"id":"1234_??_???" -> "id":"1234_0_0"
"id":"1234_foo" -> "id":"1234_0_0"
"id":"1234_567_foo" -> "id":"1234_567_0"
For Example:
If I receive json like this:
{
"identifier":{
"id":"1234",
"timestamp":"12:34:56",
},
"information":[
{
"fieldName":"test_name",
"fieldId":"test_fieldId",
}
]
}
I would want to modify it so I end up with a json like this:
{
"identifier":{
"id":"1234_0_0",
"timestamp":"12:34:56",
},
"information":[
{
"fieldName":"test_name",
"fieldId":"test_fieldId",
}
]
}
What would be the most effective/cleanest way to achieve this type of json modification in Scala?
Below is how it can be done with the Dijon library.
import com.github.pathikrit.dijon._
def normalize(id: String): String =
id.count(_ == '_') match {
case 0 => id + "_0_0"
case 1 => id + "_0"
case _ => id
}
val json =
json"""
{
"identifier":{
"id":"1234",
"timestamp":"12:34:56"
},
"information":[
{
"fieldName":"test_name",
"fieldId":"test_fieldId"
}
]
}"""
json.identifier.id = json.identifier.id.asString.fold("0_0_0")(normalize)
println(pretty(json))
It should print:
{
"identifier": {
"id": "1234_0_0",
"timestamp": "12:34:56"
},
"information": [
{
"fieldName": "test_name",
"fieldId": "test_fieldId"
}
]
}

Create a new JSON after manipulating json values in angular6

Below is my JSON
[
{
"Key": "doc/1996-78/ERROR-doc-20200103.xlsx"
}
},
{
"Key": "doc/1996-78/SUCCESS-doc-20200103.xlsx"
},
{
"Key": "doc/1996-78/PENDING-doc-20200103.xlsx"
}
]
First i want to split key value by backslash and after that will split the [2] json value by hyphen and then will check in string that if there is SUCCESS/PENDING/ERROR word found in the newly spitted JSON. If any word is present would like to add new status field and add Done/Processing/Failure respective values in newly created JSON. this is a dynamic json so without manipulating it i can't get status value
This is what i would like to achive in my new JSON
[
{
"Key": "doc/1996-78/ERROR-doc-20200103.xlsx",
"status":"Failure"
}
},
{
"Key": "doc/1996-78/SUCCESS-doc-20200103.xlsx",
"Status":"Done"
},
{
"Key": "doc/1996-78/PENDING-doc-20200103.xlsx",
"Status":"Processing"
}
]
As i'm new to this kindly let me know how to achieve this
You can use includes function and if true then add string.
Try my code:
let myJson = [
{
"Key": "doc/1996-78/ERROR-doc-20200103.xlsx"
},
{
"Key": "doc/1996-78/SUCCESS-doc-20200103.xlsx"
},
{
"Key": "doc/1996-78/PENDING-doc-20200103.xlsx"
},
{
"Key": "doc/1996-78/WRONG-doc-20200103.xlsx"
}
];
myJson = myJson.map(obj => ({
...obj,
"Status": obj.Key.includes("ERROR") ? 'Failure' : obj.Key.includes('SUCCESS') ? 'Done' : obj.Key.includes('PENDING') ? 'Processing' : false
}))
console.log(myJson)
for(let object of objectArra) {
if(object.key === 'doc....')
object['status']="Failure";
else if (object.key === 'doc..')
object['status'] = "Done";
else if....
}
Iterate on object array if the key is equal to that you want status is "failure", you insert a status property in the object with "Failure" as value ...
This can be achieved in the following way
yourArrayName.forEach((val)=>{
if(val.Key.includes('ERROR')){
val['Status']="Failure"
}
else if(val.Key.includes('SUCCESS')){
val['Status']="Done"
}
else if(val.Key.includes('PENDING')){
val['Status']="Processing"
}
})
Hope it helps!
How to do it in ES 6
The key advantage is the use of Regex which makes it more flexible to other requirements than includes.
const data = [
{
"Key": "doc/1996-78/ERROR-doc-20200103.xlsx"
},
{
"Key": "doc/1996-78/SUCCESS-doc-20200103.xlsx"
},
{
"Key": "doc/1996-78/PENDING-doc-20200103.xlsx"
}
];
data.map((entry) => {
let status;
if (/^.*ERROR.*$/.test(entry.Key)) {
status = 'Failure';
} else if (/^.*SUCCESS.*$/.test(entry.Key)) {
status = 'Done'
} else if (/^.*PENDING.*$/.test(entry.Key)) {
status = 'Processing'
}
return {...entry, status};
});

Convert JSON to Gpath result

I want to convert all the JSON key values the Map. Where I need key as gpath result and value as object key value.
Input Json
{
"employees": {
"employee": [{
"id": "1",
"firstName": "Tom",
"lastName": "Cruise",
"photo": "https://pbs.twimg.com/profile_images/735509975649378305/B81JwLT7.jpg"
},
{
"id": "2",
"firstName": "Maria",
"lastName": "Sharapova",
"photo": "https://pbs.twimg.com/profile_images/3424509849/bfa1b9121afc39d1dcdb53cfc423bf12.jpeg"
},
{
"id": "3",
"firstName": "James",
"lastName": "Bond",
"photo": "https://pbs.twimg.com/profile_images/664886718559076352/M00cOLrh.jpg"
}
]
}
}
Output I am expecting,
[employees.employee[0].id:"1",
employees.employee[0].firstName:"tom",
....]
I have tried Groovy jsonSurper() object class but I am unable to find solution to map all keys into gpath.
Any help will be appreciated!
Bit of an odd request... Can't think of why you'd want to do it... but anyway, you'd need to write some logic to recurse through the map generated by JsonSlurper, and collapse the keys...
Assuming your above json is in a String variable json:
def map = new JsonSlurper().parseText(json)
def collapseKey(String prefix, Map result, value) {
if (value instanceof Map) {
value.each { k, v ->
collapseKey("${prefix ? "${prefix}." : ''}$k", result, v)
}
} else if (value instanceof List) {
value.eachWithIndex{ e, idx ->
collapseKey("${prefix}[$idx]", result, e)
}
} else {
result."$prefix" = value
}
result
}
def result = collapseKey("", [:], map)
You could (of course) just parse it into a map and do:
map.employees.employee[0].firstName

Flutter and Json Retrieve a Title where value is

I have a Json array that is from wordpress. It retrives posts.
Each post has a serie of custom_options.
here an example:
{
"options":{
"wpcf-fields-select-option-f1d645c9017cce89714ede343df0cc73-1":{
"title":"-Select-",
"value":""
},
"wpcf-fields-select-option-3e64c784ce30a384e5167d1d6c1feb4e-1":{
"title":"1\/5",
"value":"S14"
},
"wpcf-fields-select-option-48334e061de93e6c47cc42c0fb5cd180-1":{
"title":"1\/8",
"value":"S1"
},
"wpcf-fields-select-option-a061ee2d2d302c5f42b2c93f9e811cdc-1":{
"title":"1\/12",
"value":"S2"
}
}
}
What I am trying to do is to call a function that will return the title of a given value.
Already tried using
// infoList is the json object
// resultVal is the value I am searching for
String getarrayinfos (infoList, resultVal) {
var result;
Map thisList = infoList;
for(var eachArr in thisList.keys){
if(thisList[eachArr]["value"] == resultVal){
result = thisList[eachArr]["title"];
}
}
return result.toString();
}
and printing it as the child of a container
// options is the json Object
// S7 is the value I am searching for
child: Text(getarrayinfos(options, "S7")),
but it prints the following error
flutter: type 'String' is not a subtype of type 'int' of 'index'
What am I doing wrong?
Instead of looking in infoList.keys look into infoList.values:
String getArrayInfo(Map theMap, String searchText) {
for (var val in theMap['options'].values) {
if (val['value'] == searchText) return (val['title']);
}
return 'not found';
}
void main() {
Map myMap = {
"options": {
"wpcf-fields-select-option-f1d645c9017cce89714ede343df0cc73-1": {
"title": "-Select-",
"value": ""
},
"wpcf-fields-select-option-3e64c784ce30a384e5167d1d6c1feb4e-1": {
"title": "1\/5",
"value": "S14"
},
"wpcf-fields-select-option-48334e061de93e6c47cc42c0fb5cd180-1": {
"title": "1\/8",
"value": "S1"
},
"wpcf-fields-select-option-a061ee2d2d302c5f42b2c93f9e811cdc-1": {
"title": "1\/12",
"value": "S2"
}
}
};
print(getArrayInfo(myMap, "S14"));
}

How to parse Json array object?

I am trying to parse a Json file in Qt application but i am stuck at a point.
I have a json file which contains arrays with properties. Now i have a Category class which has a items as member variable. Now i would like to parse the properties and create a unique category object and under this object i would like to add the properties.
I have achieved this by hardcoding:
auto vehicle = std::make_unique<Item>("Coordinates");
vehicle->addEntry(std::make_unique<PropertyItem>("TODO", "x", PropertyType::FLOAT, false, *vehicle.get()));
categories.emplace_back(std::move(vehicle));
void Model::loadItemsFromJson() {
// Vehicle
QJsonObject obj = loadJsonFile(":/jsonfiles/vehicle.json");
QJsonArray properties = obj["properties"].toArray();
/// No idea here how to achive
}
Should i change the Json for better handling or could this be achieved easily?
Thank you
--------------------------EDIT---------------------
Now my json looks like this:
{
"General": [{
"Address": "TODO",
"Readonly": false
},
],
"Coordinates": [{
"Address": "TODO",
"Readonly": false
}
]
]
}
and my implementation:
QJsonObject obj = loadJsonFile(":/jsonfiles/vehicle.json");
QVariantMap map = obj.toVariantMap();
for (auto& m : map.keys()) {
// How to create objects??
}
If you structure your JSON like your objects, e.g.
{
"Categories" : {
"General" : [{
"Address" : "TODO",
"Name" : "Name",
"Type" : "string",
"ReadOnly" : "true"
}, ...],
"World Coordinates" : [...]
}
Then you just parse out each CategoryItem and ScenarioPropertyItem
PropertyType toPropertyType(QJsonValue value); // forward declare
void ScenarioPropertiesModel::loadItemsFromJson() {
// Vehicle
QJsonObject obj = loadJsonFile(":/jsonfiles/vehicle.json")["Categories"].toObject();
for (auto & cat : obj)
{
auto category = std::make_unique<CategoryItem>(cat.name());
for (auto & prop : cat.value().toArray())
{
auto address = prop["Address"].toString();
auto name = prop["Name"].toString();
auto type = toPropertyType(prop["Type"]);
auto readonly = prop["Readonly"].toBool();
category->addEntry(std::make_unique<ScenarioPropertyItem>(address, name, type, readonly));
}
categories.emplace_back(std::move(category));
}
}
PropertyType toPropertyType(QJsonValue value)
{
static std::map<QString, PropertyType> propertyTypes =
{
{ "float", PropertyType::FLOAT },
{ "string", PropertyType::String },
// etc
}
return propertyTypes[value.toString()];
}