To extract specific key into a list from JSON - json

How do i extract the values of terms in below JSON into a list in opposite order. In this example i want the output to be ["Auto Ontology","hdfc bank","giftplus card"].
{
"faqs": [
{
"question": "Can the value of the HDFC Bank Giftplus card be topped up?",
"alternateQuestions": [
],
"terms": [
"giftplus card",
"hdfc bank",
"Auto Ontology"
],
"tags": [
],
"refId": "7aea18a1-32c8-5af4-8d77-da31f9c7ff26",
"responseType": "message",
"answer": [
{
"text": "Gifting we believe is special to the occasion and hence you cannot reload this card. Every occasion is a new occasion and deserves a new card.",
"type": "basic",
"channel": "default"
}
],
"alternateAnswers": [
]
},**strong text**

{
"faqs": [
{
"question": "Can the value of the HDFC Bank Giftplus card be topped up?",
"alternateQuestions": [
],
"terms": [
"giftplus card",
"hdfc bank",
"Auto Ontology"
],
"tags": [
],
"refId": "7aea18a1-32c8-5af4-8d77-da31f9c7ff26",
"responseType": "message",
"answer": [
{
"text": "Gifting we believe is special to the occasion and hence you cannot reload this card. Every occasion is a new occasion and deserves a new card.",
"type": "basic",
"channel": "default"
}
],
"alternateAnswers": [
]
}
]
}
You can use the python code given below To print opposite order
import json
f = open('rev.json', 'r')
a = json.load(f)
b = a["faqs"][0]["terms"][::-1]
print(b)
Output:
['Auto Ontology', 'hdfc bank', 'giftplus card']

You may try to use the snippet
Var = a["faqs"][0]["terms"][::-1]
The ::-1 is used to reverse the output.

Related

Snowflake - Querying Nested JSON

I need some help querying this JSON file I've ingested into a temp table in Snowflake. So, I've created a JSON_DATA variant column and plan to query and do a COPY INTO another table, but my query isn't working yet... I feel I'm close (possibly?)
JSON layout:
{
"nextPage": "01",
"page": "0",
"status": "ok",
"transactions": [
{
"id": "65985",
"recordTp": "vendorbill",
"values": {
"account": [
{
"text": "14500 Deferred Expenses",
"value": "249"
}
],
"account.number": "1450",
"account.type": [
{
"text": "Deferred Expense",
"value": "DeferExpense"
}
],
"amount": "51733",
"classnohierarchy": [
{
"text": "901 Corporate",
"value": "139"
}
],
"currency": [
{
"text": "Canadian Dollar",
"value": "3"
}
],
"customer.altname": "V Sties expenses (Tor)",
"customer.custate": "12/31/2019",
"customer.custentient": "ada Inc.",
"customer.custendate": "1/1/2019",
"customer.entyid": "PR781",
"departmentnohierarchy": [
{
"text": "8rity",
"value": "37"
}
],
"fxamount": "689",
"location": [
{
"text": "Othad Projects",
"value": "48"
}
],
"postingperiod": [
{
"text": "Jan 2020",
"value": "1"
}
],
"subsidiary.custrecord_region": [
{
"text": "CANADA",
"value": "3"
}
],
"subsidiarynohierarchy": [
{
"text": "ada Inc.",
"value": "25"
}
]
}
},
I've been able to query the values that are not (deeply) nested but I need help getting, for example, the values from 'classnohierarchy', to get both the 'text' and 'value' I tried:
transactions.value:"values".classnohierarchy.text::string as class_txt,
transactions.value:"values".classnohierarchy.value::string as class_val,
but it's returning NULL values.
Below is my entire query:
SELECT
JSON_DATA:status::string as connection_status,
transactions.value:id::string as id,
transactions.value:recordType::string as record_type,
transactions.value:"values"::variant as trans_val,
transactions.value:"values".account as acc,
transactions.value:"values".account.text as text,
transactions.value:"values".account.value as val,
transactions.value:"values"."account.number"::string as acc_num,
transactions.value:"values"."account.type".text::string as acc_type_txt,
transactions.value:"values"."account.type".value::string as acc_type_val,
transactions.value:"values".amount::string as amount,
**transactions.value:"values".classnohierarchy.text::string as class_txt,
transactions.value:"values".classnohierarchy.value::string as class_val,**
transactions.value:"values".currency.text::string as currency_text,
transactions.value:"values".currency.value::string as currency_val,
transactions.value:"values"."customer.altname"::string as customer_project_name,
transactions.value:"values"."customer.custate"::string as customer_end_date,
transactions.value:"values"."customer.custentient"::string as customer_end_client,
transactions.value:"values"."customer.custendate"::string as customer_start_date,
transactions.value:"values"."customer.entyid"::string as customer_project_id,
transactions.value:"values".departmentnohierarchy.text::string as department_name,
transactions.value:"values".departmentnohierarchy.value::string as department_value,
transactions.value:"values".fxamount::string as fx_amount,
transactions.value:"values".location.text::string as product_name,
transactions.value:"values".postingperiod.text::string as postingperiod,
transactions.value:"values".postingperiod.value::string as postingperiod,
transactions.value:"values"."subsidiary.custrecord_region".text::string as region_name,
transactions.value:"values"."subsidiary.custrecord_region".value::string as region_value,
transactions.value:"values".subsidiarynohierarchy.text::string as entity_name,
transactions.value:"values".subsidiarynohierarchy.value::string as entity_value,
FROM MY_TABLE,
LATERAL FLATTEN (JSON_DATA:transactions) as transactions
and here's a picture of whats showing in Snowflake:
SNOWFLAKE_SCREENSHOT
departmentnohierarchy is an array. you need to mention the index as below.
select *,transactions.VALUE:"values".departmentnohierarchy[0].value::text as department_name
FROM jsont1,
LATERAL FLATTEN (JSON_DATA:transactions) as transactions

How to save data in Json format in React-admin v3?

I created JsonInput, which sends a json object to the input SimpleForm, however, a modified version of it gets into the Data Provider.
that's what is sent to the input:
json: {
"FunctionalGroup": [
{
"uaIDref": [
"2104"
],
"_Name": "Текущие параметры",
"_ID": "33"
},
{
"uaIDref": [
"2100"
],
"_Name": "Текущие параметры пониженной точности",
"_ID": "34"
},
],
"_Name": "Прибор 1",
"_ID": "32"
}
that's what came to the server:
json: {
"FunctionalGroup": [
{
"uaIDref": [
"2104"
],
"_Name": "Текущие параметры",
"_ID": "33"
},
{
"uaIDref": [
"2100"
],
"_Name": "Текущие параметры пониженной точности",
"_ID": "34"
}
],
"FunctionalGroupIds": "",
"_Name": "Прибор 1",
"_ID": "32"
},
after a response from the server with this object, this is what came in the field:
json: {
FunctionalGroup: [
{
uaIDref: [
'2104'
]
},
{
uaIDref: [
'2100'
]
}
],
FunctionalGroupIds: ''
}
what kind of magic is this?
I did some tests. When I converted the object to a string, the correct json was sent to the server, however, in the field after the server responded, the modified object was displayed again.
I found out that the conversion is related to redux.js, but what exactly happens is not understood.
Please give any comments on this.
How can I make save json?

react native json image

I want to print out JSON images as a variable.
This is my local JSON file (JsonData.json):
{
"appetizer": [
{
"num": "appetizer1",
"name": "salad",
"condition": [ "1", "2" ],
"image": "./appetizer/salad.png"
},
{
"num": "appetizer2",
"name": "soup",
"condition": [ "2", "3" ],
"image": "./appetizer/soup.png"
},
…
],
"main": [
{
"num": "main1",
"name": "beef",
"condition": [ "1" ],
"image": "./main/beef.png"
},
{
"num": "main2",
"name": "fish",
"condition": [ "2", "3" ],
"image": "./main/fish.png"
},
…
]
}
I filtered the name when condition="2". (salad,soup,fish)
This is the code for filtering name:
const newArray1 = [...JsonData["apptizer"], ...JsonData["main"]];
const JsonResult = newArray1.filter(item => {
if(item.condition.indexOf("2") !== -1) return item.name;
});
AND I want to get the image when condition="2".
How can I get them? And How can I print out them?
Do I have to use base64? If so, Can you tell me how to use it?
I saw the explanation, but I can't understand it.
And I imported JSON file this way (I've been correctly using it):
var JsonData = require('./JsonData.json');
You can use below code:
let mainObject = JSON.parse(JSON.stringify(data))
let allKeys = Object.keys(mainObject)
let finalObject = []
allKeys.map((value, index) => {
let array = mainObject[value]
array.map((aryObject, aryIndex) => {
let condition = aryObject['condition']
if (condition.includes('2')) {
finalObject.push(aryObject)
}
})
})
alert(JSON.stringify(finalObject))
You can import data in top of screen:
import { data } from './data';
You can add below text in data.js:
export const data = {
"appetizer": [
{
"num": "appetizer1",
"name": "salad",
"condition": ["1"],
"image": "./appetizer/salad.png"
},
{
"num": "appetizer2222",
"name": "soup",
"condition": ["2", "3"],
"image": "./appetizer/soup.png"
},
],
"main": [
{
"num": "main1",
"name": "beef",
"condition": ["1"],
"image": "./main/beef.png"
},
{
"num": "main2",
"name": "fish",
"condition": ["21", "3"],
"image": "./main/fish.png"
},
]
}
You can use Object#values to get the arrays corresponding to appetizer and main and then Array#flat to extract the nested objects into a transformed array. Then use the Array#filter (which you are already using) to filter out only the required objects based on your condition and then Array#map to get the name and image values out of every filtered object into an array of objects.
Please consider following snippts
const jsonData = {"appetizer":[{"num":"appetizer1","name":"salad","condition":["1","2"],"image":"./appetizer/salad.png"},{"num":"appetizer2","name":"soup","condition":["2","3"],"image":"./appetizer/soup.png"}],"main":[{"num":"main1","name":"beef","condition":["1"],"image":"./main/beef.png"},{"num":"main2","name":"fish","condition":["2","3"],"image":"./main/fish.png"}]};
const filteredValues = Object.values(jsonData)
.flat()
.filter(o => o.condition.includes('2'))
.map(({name, image}) => ({ name, image }));
console.log(filteredValues);
The output of the above code will be an array of objects having the following structure
[{
"name": SOME_NAME,
"image": SOME_PATH
},
{
"name": SOME_NAME,
"image": SOME_PATH
},
...
]
You can use the above array to retrieve your image path and display it accordingly.
I think you shouldn't be worried about base64 as images are stored locally and path will be sufficient to display the image.
Hope this will help!!!
Side Note: You can avoid the Array#flat part as you are already doing it manually [...JsonData["apptizer"], ...JsonData["main"]] but flat will be handy in case there are more keys in jsonData that need to be considered.

Parse data from JSON in ReactJS

I have data like this:
{
"movies": [
{
"abridged_cast": [
{
"characters": [
"Dominic Toretto"
],
"id": "162652472",
"name": "Vin Diesel"
},
{
"characters": [
"Brian O'Conner"
],
"id": "162654234",
"name": "Paul Walker"
},
{
"characters": [
"Louie Tran"
],
"id": "162684066",
"name": "Tony Jaa"
},
{
"characters": [
"Deckard Shaw"
],
"id": "162653720",
"name": "Jason Statham"
},
{
"characters": [
"Luke Hobbs"
],
"id": "770893686",
"name": "Dwayne \"The Rock\" Johnson"
}
],
"alternate_ids": {
"imdb": "2820852"
},
"critics_consensus": "",
"id": "771354922",
"links": {
"alternate": "http://www.rottentomatoes.com/m/furious_7/",
"cast": "http://api.rottentomatoes.com/api/public/v1.0/movies/771354922/cast.json",
"reviews": "http://api.rottentomatoes.com/api/public/v1.0/movies/771354922/reviews.json",
"self": "http://api.rottentomatoes.com/api/public/v1.0/movies/771354922.json",
"similar": "http://api.rottentomatoes.com/api/public/v1.0/movies/771354922/similar.json"
},
"mpaa_rating": "PG-13",
"posters": {
"detailed": "http://resizing.flixster.com/pVDoql2vCTzNNu0t6z0EUlE5G_c=/51x81/dkpu1ddg7pbsk.cloudfront.net/movie/11/18/14/11181482_ori.jpg",
"original": "http://resizing.flixster.com/pVDoql2vCTzNNu0t6z0EUlE5G_c=/51x81/dkpu1ddg7pbsk.cloudfront.net/movie/11/18/14/11181482_ori.jpg",
"profile": "http://resizing.flixster.com/pVDoql2vCTzNNu0t6z0EUlE5G_c=/51x81/dkpu1ddg7pbsk.cloudfront.net/movie/11/18/14/11181482_ori.jpg",
"thumbnail": "http://resizing.flixster.com/pVDoql2vCTzNNu0t6z0EUlE5G_c=/51x81/dkpu1ddg7pbsk.cloudfront.net/movie/11/18/14/11181482_ori.jpg"
},
"ratings": {
"audience_rating": "Upright",
"audience_score": 88,
"critics_rating": "Certified Fresh",
"critics_score": 82
},
"release_dates": {
"theater": "2015-04-03"
},
"runtime": 140,
"synopsis": "Continuing the global exploits in the unstoppable franchise built on speed, Vin Diesel, Paul Walker and Dwayne Johnson lead the returning cast of Fast & Furious 7. James Wan directs this chapter of the hugely successful series that also welcomes back favorites Michelle Rodriguez, Jordana Brewster, Tyrese Gibson, Chris \"Ludacris\" Bridges, Elsa Pataky and Lucas Black. They are joined by international action stars new to the franchise including Jason Statham, Djimon Hounsou, Tony Jaa, Ronda Rousey and Kurt Russell.",
"title": "Furious 7",
"year": 2015
}
]
}
I need to parse all data from all fields from this JSON file. Is there a way to do it in React JS? Could you please suggest me any way to parse data from a structured JSON file like this?
React lives in JavaScript. So parsing a JSON string is done with:
var myObject = JSON.parse(myjsonstring);
How to fetch a file from somewhere with AJAX is a different question.
You could use fetch() for this. See for example
https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API or
https://davidwalsh.name/fetch or
https://blog.gospodarets.com/fetch_in_action

creating JSON object without using a list

I want to be able to create a JSON object so that I can access it like this.
education.schools.UNCC.graduation
Currently, my JSON is like this:
var education = {
"schools": [
"UNCC": {
"graduation": 2015,
"city": "Charlotte, NC",
"major": ["CS", "Spanish"]
},
"UNC-CH": {
"graduation": 2012,
"city": "Chapel Hill, NC"
"major": ["Sociology", "Film"]
}
],
"online": {
"website": "Udacity",
"courses": ["python", "java", "data science"]
}
};
When I go to Lint my JSON, I get an error message.
I know I can reformat my object to access it like this (below), but I don't want to do it this way. I want to be able to call the school name, and not use an index number.
education.schools[1].graduation
Objects have named keys. Arrays are a list of members.
Replace the value of "schools" with an object. Change [] to {}.
This is your JSON corrected.
Your JSON is invalid.
{
"schools": [
{
"UNCC": {
"graduation": "2015",
"city": [
"CS",
"Spanish"
],
"major": [
"CS",
"Spanish"
]
}
},
{
"UNC-CH": {
"graduation": "2012",
"city": [
"Chapel Hill",
"NC"
],
"major": [
"Sociology",
"Film"
]
}
}
],
"online": {
"website": "Udacity",
"courses": [
"python",
"java",
"data science"
]
}
}
Explanation:
"city": "Chapel Hill, NC" -> this is a array with 2 values "Chapel Hill" and "HC", like you do with major and courses.
The Schools array, you need to use this sintaxe to construct a array [{
http://adobe.github.io/Spry/samples/data_region/JSONDataSetSample.html