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"));
}
Related
I'm trying to extract data from an API call that gives me this JSON:
JSON data:
{ "rows":
[
{
"customer_id": 1,
"customer_details":
{
"customer_id": 1,
"email":"john#mail.com",
"first_name":"John",
"last_name":"Doe",
"phone":"+123456123"
},
"order_items":[
{
"name": "random name",
"quantity":1
}
]
},
{
"customer_id": 2,
"customer_details":
{
"customer_id": 2,
"email":"johnny#mail.com",
"first_name":"Johnny",
"last_name":"Silverhand",
"phone":"+123456123"
},
"order_items":[
{
"name": "random name",
"quantity":1
},
{
"name": "another random name",
"quantity":1
}
]
}
]
}
I am actually able to get the the quantity but when there are two or more objects from the array in order_items like with customer 2, what I get is 11 how do I add the values I get? Sorry if this is really a simple problem but I am really confused.
here is my code for how I get them:
function getQuantity(qty) {
if(qty.length === 1) {
return qty[0].quantity;
} else {
let tempArr = [];
qty.forEach(prod => {
// console.log(prod.quantity)
tempArr.push(prod.quantity)
});
return tempArr;
}
}
I mapped used the function I made inside a map here is part of the code:
{orderList.map((val, key) => {
if (val.status_id !== 5) {
return (
<tr key={key} className='text-center'>
<td className='tdata'>{getQuantity(val.order_items)}</td>
Your getQuantity function returns an array of numbers (given this json data) and when you set the value of your td to be, as in your example, [1, 1] it will output "1""1" which will look like "11".
If you want to display the sum of your values, you could do something like this (although there is probably a better way to sum all the numbers in an array)
function getQuantity(qty) {
if(qty.length === 1) {
return qty[0].quantity;
} else {
let tempVal = 0;
qty.forEach(prod => {
tempVal += prod.quantity
});
return tempVal;
}
}
I am trying to get a value from a JSON file, however it is a complex JSON file and i'm not sure how to go about it.
The value is situated inside an object, that is inside another object, which inside another object.
The values I want to retrieve from the JSON file is "value" and "unit" situated inside the object "metric". I have been able to successfully retrieve the "name" value.
The JSON file:
{
"ingredients": [
{
"name": "breakfast sausage",
"image": "breakfast-sausage-links.jpg",
"amount": {
"metric": {
"value": 226.796,
"unit": "g"
},
"us": {
"value": 8,
"unit": "ounces"
}
}
},
I will also include the method that I parse the JSON from:
private void jsonParse(){
String url = "https://api.spoonacular.com/recipes/"+ rMealId + "/ingredientWidget.json?&apiKey=da7dd16a704f4552b70a96c1e9641b08";
RequestQueue requestQueue = Volley.newRequestQueue(this);
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("ingredients");
for(int i = 0; i < jsonArray.length(); i++){
JSONObject ingredients = jsonArray.getJSONObject(i);
String iName = ingredients.getString("name");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
Log.e("Volley", error.toString());
}
});
requestQueue.add(request);
}
Just focusing on your json string, try this:
let ings =
{
"ingredients": [
{
"name": "breakfast sausage",
"image": "breakfast-sausage-links.jpg",
"amount": {
"metric": {
"value": 226.796,
"unit": "g"
},
"us": {
"value": 8,
"unit": "ounces"
}
}
}
]
}
let jp = require('jsonpath');
let eat = jp.query(ings, '$..metric.*');
console.log(eat);
output:
[ 226.796, 'g' ]
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};
});
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"}
}
})
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