Unable to display data from json.net - json

Can anyone help solve this problem, no matter what i try i cannot display the data on webpage, i can put a breakpoints at JObject o = JObject.Parse(ws); and see the data, but every attempt i have tried results in a different error.I'm trying to do is get the areaName and country.
I have tried the examples from: http://james.newtonking.com/projects/json/help/ and http://forums.asp.net/t/1780822.aspx/1?How+to+traverse+in+json+ with no luck
Any help would be appreciated.
George
My code is below:
string ws = #"{ ""search_api"": { ""result"": [ { ""areaName"": [ {""value"": ""London"" } ], ""country"": [ {""value"": ""United Kingdom"" } ], ""latitude"": ""51.517"", ""longitude"": ""-0.106"", ""population"": ""7421228"", ""region"": [ {""value"": ""City Of London, Greater London"" } ], ""timezone"": [ {""offset"": ""1.0"" } ], ""weatherUrl"": [ {""value"": ""http:\/\/www.worldweatheronline.com\/London-weather\/City-of-London-Greater-London\/GB.aspx"" } ] }, { ""areaName"": [ {""value"": ""London"" } ], ""country"": [ {""value"": ""Canada"" } ], ""latitude"": ""42.983"", ""longitude"": ""-81.250"", ""population"": ""346774"", ""region"": [ {""value"": ""Ontario"" } ], ""timezone"": [ {""offset"": ""-4.0"" } ], ""weatherUrl"": [ {""value"": ""http:\/\/www.worldweatheronline.com\/London-weather\/Ontario\/CA.aspx"" } ] } ] }}";
JObject o = JObject.Parse(ws);
var weatherCity = o["areaName"][0]["value"];
ViewBag.WeatherSearch = weatherCity.ToString();
//var weatherCity = o["search_api"][0]["result"]["areaName"]["value"];
// JArray arr = (JArray)o.SelectToken("search_api");
// JObject cityTown = (JObject)arr[0].SelectToken("result").SelectToken("areaName");
// var weatherCity = cityTown.SelectToken("value");
// IList<string> WeatherCity = o.SelectToken("result").Select(s => (string)s).ToList();
//string WeatherCity = (string)o.SelectToken("result[0].areaName[0].value");
//IList<string> WeatherCities = o["result"].Select(m => (string)m.SelectToken("areaName[0].value")).ToList();

How about something like:
var weatherCity = o["search_api"]["result"][0]["areaName"][0]["value"];
o represents the root, so you can't skip any nodes.

Related

Adding values to 2D array with forEach

I am trying to add values to a 2D array in Google Apps Script. The following code runs, but is not the desired output for the array.
function fruitList() {
var fruitArray = [['apple'], ['banana'], ['cherry']];
var newArray = [];
fruitArray.forEach(function(value) {
newArray.push([value, "name"]);
});
}
My code yields the following output:
[ [ [ 'apple' ], 'name' ], [ [ 'banana' ], 'name' ], [ [ 'cherry' ], 'name' ] ]
My desired output is:
[ [ 'apple', 'name' ], [ 'banana', 'name' ], [ 'cherry', 'name' ] ]
value is a array. Not a string/primitive value. You can use destructuring assignment to get the actual value:
fruitArray.forEach(function([/*destructure 1D array*/value]) {
newArray.push([value, "name"]);
});
/*<ignore>*/console.config({maximize:true,timeStamps:false,autoScroll:false});/*</ignore>*/
function fruitList() {
var fruitArray = [['apple'], ['banana'], ['cherry']];
var newArray = [];
fruitArray.forEach(function([value]) {
newArray.push([value, "name"]);
});
console.info(newArray)
}
fruitList()
<!-- https://meta.stackoverflow.com/a/375985/ --> <script src="https://gh-canon.github.io/stack-snippet-console/console.min.js"></script>
Add a value:
function fruitList() {
var fruitArray = [['apple'], ['banana'], ['cherry']];
var newArray = [];
fruitArray.forEach(function(value) {
newArray.push([value[0], "name"]);
});
Logger.log(JSON.stringify(newArray))
}
Execution log
3:27:33 PM Notice Execution started
3:27:34 PM Info [["apple","name"],["banana","name"],["cherry","name"]]
3:27:34 PM Notice Execution completed

How to export the api call results to a csv with the values of single response in one row?

My api response looks like below
[
{
"What time is it?": [
"option_2"
]
},
{
"When will we go home?": [
"option_1"
]
},
{
"When is your birthday?": [
"2050"
]
},
{
"How much do you sleep?": [
"Ajajajsjiskskskskdkdj"
]
}
],
[
{
"What time is it?": [
"option_2"
]
},
{
"When will we go home?": [
"option_1"
]
},
{
"When is your birthday?": [
"10181"
]
},
{
"How much do you sleep?": [
"Ajskossooskdncpqpqpwkdkdkskkskskksksksksks"
]
}
]
Now in react, I want to export the results to a csv. I can do it by export-to-csv but the formatting is the issue here. I want the values of each question of a single response in one row under their labels(questions). So if I have two response like above I want to have export it in two rows, not 8 as there are 8 total questions.
Here is how I want it to get exported.
I have tried so far like this but no luck.
this is my export data function
exp =()=>{
const raw = []
console.log(this.state.data[0].sbm_id)
axios.get(`/dashboard/${this.props.proj_id}/whole_sub/`)
.then(res=>{
// console.log('1')
// console.log(res.data[0][0])
// console.log('2')
for (let i =0;i<this.state.data.length;i++){
for(let j = 0;j<res.data[0].length;j++){
// let sub=[]
//res.data[i][j].ID = this.state.data[i].sbm_id
raw.push(res.data[i][j])
}
}
}
)
let curr = this.state
curr.exp = raw
this.setState({exp:curr.exp})
}
Here is my export function
rawExport=()=>{
const csvExporter = new ExportToCsv(optionsExp);
csvExporter.generateCsv(this.state.exp);
}
First step is to flatten the initial nested array to get a homogeneously shaped array, then you keep on reducing it further.
const data = [
[
{
"What time is it?": [
"option_2"
]
},
{
"When will we go home?": [
"option_1"
]
},
{
"When is your birthday?": [
"2050"
]
},
{
"How much do you sleep?": [
"Ajajajsjiskskskskdkdj"
]
}
],
[
{
"What time is it?": [
"option_2"
]
},
{
"When will we go home?": [
"option_1"
]
},
{
"When is your birthday?": [
"10181"
]
},
{
"How much do you sleep?": [
"Ajskossooskdncpqpqpwkdkdkskkskskksksksksks"
]
}
]
];
const flattenArray = (arr) => [].concat.apply([], arr);
// Flatten the initial array
const flattenedArray = flattenArray(data);
// Keep on reducing the flattened array into an object
var res = flattenedArray.reduce((acc, curr) => {
const [key, val] = flattenArray(Object.entries(curr));
if (!acc[key]) {
acc[key] = [].concat(val);
} else {
val.forEach(x => {
if (!acc[key].includes(x)) {
acc[key].push(x);
}
});
}
return acc;
}, {});
console.log(res);

file_get_contents parse json insert database

Hi I encountered a problem. I will record the data I received from the database.
JSON=>
{
"success": true,
"timestamp": 1565251506,
"base": "EUR",
"date": "2019-08-08",
"rates": {
"AED": 4.119657,
"AFN": 87.689574,
"ALL": 121.192477,
"AMD": 533.113395,
"ANG": 1.998509,
"AOA": 398.760307,
"ARS": 51.036305,
"AUD": 1.654423
}
}
After Json decode
array:5 [
"success" => true
"timestamp" => 1565205306
"base" => "EUR"
"date" => "2019-08-07"
"rates" => array:168 [
"AED" => 4.118588
"AFN" => 87.74397
"ALL" => 121.002609
"AMD" => 534.279745
"ANG" => 2.001014
]
]
I want this=> But How do I get quote and rate?
$response = file_get_contents("rate.json");
$datas = json_decode($response, true);
foreach ($datas as $data) {
$rates = new Rate();
$rates->base = $datas['base'];
$rates->quote = 'AED';
$rates->rate = '4.119657';
$rates->save();
}
You're looping over the wrong thing here, you should be looping over the rates and saving the corresponding key and value:
$response = file_get_contents("rate.json");
$data = json_decode($response, true);
foreach ($data['rates'] as $quote => $rate) {
$rates = new Rate();
$rates->base = $data['base'];
$rates->quote = $quote;
$rates->rate = $rate;
$rates->save();
}

Iterate through JSON Object to get all objects with property

I am trying to iterate through the following JSON document in order to get the names of skating rinks:
I can get one name; however, what I am trying to do is loop through all of the entries (there are 253) and return a list of all the names.
Here is my React component:
class Patinoire extends Component {
constructor(props) {
super(props);
this.state = { patinoires: [] };
}
componentDidMount() {
var url = 'http://localhost:3000/patinoires'
fetch(url).then(function(response) {
if (response.status >= 400) {
throw new Error("Bad response from server");
}
return response.json();
})
.then(data => this.setState ({ patinoires: data.patinoires }));
}
render() {
var patinoires = this.state.patinoires;
var pjs2 = Object.values(patinoires);
var pjs3 = pjs2.map(x => x["2"].nom);
return <div>{pjs3}</div>
}
}
Right now, when using {pjs3}, I get the name of 3rd skating rink of the JSON document. How can I loop through all the entries and return the name property of all the entries?
EDIT: here is a sample of the data
{
"patinoires": {
"patinoire": [
{
"nom": [
"Aire de patinage libre, De la Savane (PPL)"
],
"arrondissement": [
{
"nom_arr": [
"Côte-des-Neiges - Notre-Dame-de-Grâce"
],
"cle": [
"cdn"
],
"date_maj": [
"2018-01-12 09:08:25"
]
}
],
"ouvert": [
""
],
"deblaye": [
""
],
"arrose": [
""
],
"resurface": [
""
],
"condition": [
"Mauvaise"
]
},
{
"nom": [
"Aire de patinage libre, Georges-Saint-Pierre (PPL)"
],
"arrondissement": [
{
"nom_arr": [
"Côte-des-Neiges - Notre-Dame-de-Grâce"
],
"cle": [
"cdn"
],
"date_maj": [
"2018-01-12 09:08:25"
]
}
],
"ouvert": [
""
],
"deblaye": [
""
],
"arrose": [
""
],
"resurface": [
""
],
"condition": [
"Mauvaise"
]
}
]
}
}
You can use Array.prototype.reduce() to flatten the result data with combination of Array.prototype.map() or Array.prototype.forEach().
Here is a running example:
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
patinoires: {
patinoire: [
{
nom: ["Aire de patinage libre, De la Savane (PPL)"],
arrondissement: [
{
nom_arr: ["Côte-des-Neiges - Notre-Dame-de-Grâce"],
cle: ["cdn"],
date_maj: ["2018-01-12 09:08:25"]
}
],
ouvert: [""],
deblaye: [""],
arrose: [""],
resurface: [""],
condition: ["Mauvaise"]
},
{
nom: ["Aire de patinage libre, Georges-Saint-Pierre (PPL)"],
arrondissement: [
{
nom_arr: ["Côte-des-Neiges - Notre-Dame-de-Grâce"],
cle: ["cdn"],
date_maj: ["2018-01-12 09:08:25"]
}
],
ouvert: [""],
deblaye: [""],
arrose: [""],
resurface: [""],
condition: ["Mauvaise"]
}
]
}
};
}
renderData = () => {
const { patinoires } = this.state;
const markup = patinoires.patinoire.reduce((result, current) => {
current.nom.map(n => {
return result.push(<div>{n}</div>);
});
return result;
}, []);
return markup;
}
render() {
return <div>{this.renderData()}</div>;
}
}
ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>
Try this:
var pjs2 = Object.values(patinoires);
var names = pjs2.reduce((accumulator, elem) => {
if (elem.patinoire) {
elem.patinoire.forEach(part => {
if(part.nom) {
part.nom.forEach((name) => accumulator.push(name));
}
});
}
return accumulator;
}, []);

How to format the JSON object key/value pair

I am new to nodejs, right now I am able to fetch the data from the database and display as REST API which is of key/value pair. My output looks like as shown below
[{"id":"793","actionname":"test_bsc_interface","actionid":"100"}].
But I need to format as
{ "header" : [id,actionname,actionid],
"values" : [793 ,test_bsc_interface,100] ],}.
I tried with JSON.stringfy and checked few website but it's not working.
Could any one please help me through which link I should go through or approach.
The easy way to do it is to use underscore or lodash module to format it:
var _ = require('lodash');
var data = [{"id":"793","actionname":"test_bsc_interface","actionid":"100"}];
var result = _.map(data, function(o) {
return {headers: _.keys(o), values : _.values(o)}
});
console.dir(result);
Output is:
[
{
headers: [ 'id', 'actionname', 'actionid' ],
values: [ '793', 'test_bsc_interface', '100' ]
}
]
To get the result you want, just do result[0]
Note that I use _.map() instead of data[0] because this will work for the array (your array result from the query) that has more than 1 item.
Revised answer according to your comment (1 header line and all value lines in an array):
var _ = require('lodash');
var data = [
{ id: '714', actionname: 'test_bsc_interface', actionid: '100' },
{ id: '715', actionname: 'list_all_available_interfaces', actionid: '103' },
{ id: '716', actionname: 'check_tt', actionid: '101' }
];
var result;
if (_.size(data) > 0) {
result = {
headers: _.keys(data[0]),
values: _.map(data, function(o) {
return _.values(o);
})
};
}
console.dir(result);
and the output is:
{
headers: [ 'id', 'actionname', 'actionid' ],
values: [
[ '714', 'test_bsc_interface', '100' ],
[ '715', 'list_all_available_interfaces', '103' ],
[ '716', 'check_tt', '101' ]
]
}