How to update a key value in JSON dynamically? - json

I have a JSON like below
{
"context":{
"parameters":[
{
"name":"stub",``
"value": {"item value":"abcdefg"}
},
{
"name":"category",
"value":{"item value":"cars"}
},
{
"name":"year",
"value":{"item value":"2012"}
},
{
"name":"make",
"value":{"item value":"toyota"}
},
{
"name":"cars",
"value":{"item value":"corolla"}
}
]
}
I am supplied with a two strings dynamically like "cars" and "accord". I need to search for "cars" and then replace the "item value" under it to "accord". I have tried to convert it to map but have no success.
Any suggestions about how I can achieve this?

Here's one way to do it in Groovy.
Assuming that the JSON is like so (I have corrected it; there are illegal chars in the original question):
def s = '''
{
"context":{
"parameters":[
{
"name":"stub",
"value": {"item value":"abcdefg"}
},
{
"name":"category",
"value":{"item value":"cars"}
},
{
"name":"year",
"value":{"item value":"2012"}
},
{
"name":"make",
"value":{"item value":"toyota"}
},
{
"name":"cars",
"value":{"item value":"corolla"}
}
]
}
}
'''
then consider:
import groovy.json.*
def jsonSlurper = new JsonSlurper().parseText(s)
def category = jsonSlurper.context.parameters.find { it.name == "cars" }
category.value."item value" = "accord"
println new JsonBuilder(jsonSlurper).toPrettyString()

you can do that with javascript. If you are working with JSON format you can parse that data to an object.
const data = JSON.parse("your json data")
data.context.parameters.map(param => {
if ( param.name !== "cars") {
return param
}
return {
"name": "cars",
value: {"accord": "corolla"}
}
})

Related

How to flatten json array using typescript and Convert it as object

I am trying to convert a json array as a flat json using typescript.
I have a json as below:
"Fields" : [
{
"FieldName" : "xyz";
"FieldValue" : {
"Contents": {
" Company": "ABC"
}
}
}
]
I have to convert as below:
"xyz" : {
"Contents": {
" Company": "ABC"
}
}
Here Fields should be replaced with "xyz", FieldName and FieldValue should need to be removed.
Help me to achieve this using typescript.
If you really only want to work with that first item in your array just rearrange the data with something the following.
const json = JSON.stringify({
Fields: [
{
FieldName: "xyz",
FieldValue: {
Contents: {
" Company": "ABC"
}
}
}
]
});
const parsedJson = JSON.parse(json);
const expectedOutput = {
[parsedJson.Fields[0].FieldName]: parsedJson.Fields[0].FieldValue
};
console.log(expectedOutput);

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};
});

Parsing Groovy Json Into Key Value

I'm attempting to parse Json using Groovy's jsonslurper. I'd like to drill down into the "id" and "label" elements and create a key:value pair from them. This is my attempt:
def slurper = new groovy.json.JsonSlurper()
def json = slurper.parseText(myjson)
result = [:]
json.each {
result.put(json.menu.items.id,json.menu.items.label)
}
println result
​
What I expect is a result of:
[ [Open, null], [OpenNew, Open New], [Zoomin, Zoom In], etc....]
What I get is one list of the id's and one list of the labels. Any suggestion on how to get the desired result? Here is the Json I'm feeding...
{
"menu":{
"header":"SVG Viewer",
"items":[
{
"id":"Open"
},
{
"id":"OpenNew",
"label":"Open New"
},
null,
{
"id":"ZoomIn",
"label":"Zoom In"
},
{
"id":"ZoomOut",
"label":"Zoom Out"
},
{
"id":"OriginalView",
"label":"Original View"
},
null,
{
"id":"Quality"
},
{
"id":"Pause"
},
{
"id":"Mute"
},
null,
{
"id":"Find",
"label":"Find..."
},
{
"id":"FindAgain",
"label":"Find Again"
},
{
"id":"Copy"
},
{
"id":"CopyAgain",
"label":"Copy Again"
},
{
"id":"CopySVG",
"label":"Copy SVG"
},
{
"id":"ViewSVG",
"label":"View SVG"
},
{
"id":"ViewSource",
"label":"View Source"
},
{
"id":"SaveAs",
"label":"Save As"
},
null,
{
"id":"Help"
},
{
"id":"About",
"label":"About Adobe CVG Viewer..."
}
]
}
}
You can do this
def result = new JsonSlurper()
.parseText(json)
.menu
.items
.findAll() // Throw away the 4 `null` ones
.collect { [ it.id, it.label ] }

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"));
}