Extract variable from JSON result - json

I am trying to extract the elevation variable from the JSON response of the OpenElevation API:
coordinates = stations.iloc[2]['Lat'] + ', ' + stations.iloc[2]['Long']
url = 'https://api.open-elevation.com/api/v1/lookup?locations=' + coordinates
resp = rq.get(url)
print(resp.json())
OUTPUT: https://api.open-elevation.com/api/v1/lookup?locations=51.52128377, -0.084605692
{'results': [{'latitude': 51.52128377, 'longitude': -0.084605692, 'elevation': 27}]}
How do I extract the 'elevation' variable so I can add it to my existing dataframe (stations) in a new column.
I have already tried this:
resp = rq.get(url)
resp_dict = json.loads(resp.json)
print(resp_dict['results']['elevation'])
OUTPUT: TypeError: the JSON object must be str, bytes or bytearray, not method
And when I try to use
print(resp.json['results']['elevation']())
OUTPUT: TypeError: 'method' object is not subscriptable
I feel like the solution is pretty simple but I have not been able to figure it out.
Thanks

Related

Obtain value in json response

How do i write an expression to obtain the value "lastUpdated" in the below json response data
{"resourceType":"Parameters","parameter":[{"name":"medication","resource":{"resourceType":"Bundle","id":"956ffe6a-08ed-4cb6-82ca-41065a4a9923","meta":{"lastUpdated":"2020-08-24T19:09:18.5649325+00:00",
I have tried this but it does not work:
regex("\"lastUpdated\": \"(.*?)\"").saveAs("lastUpdated")
this also does not work:
jsonPath("$..[?(#.use==\"lastUpdated\")].value").saveAs("lastUpdated"))
Your input is a little cut off but here is what I've got:
myJSONString = '{"resourceType":"Parameters","parameter":[{"name":"medication","resource":{"resourceType":"Bundle","id":"956ffe6a-08ed-4cb6-82ca-41065a4a9923","meta":{"lastUpdated":"2020-08-24T19:09:18.5649325+00:00"}}}]}'
myJSONObject = JSON.parse(myJSONString)
myLastUpdated = myJSONObject.parameter[0].resource.meta.lastUpdated
console.log(myLastUpdated)
Basically you convert it from a json object into a javascript object. Then you can just traverse down the tree to your intended target.

How to replace a JSON value stored in a JSON file and use that in a Rest Assured test

I have a set of input data files in JSON and I am trying to replace a value present in a JSON file and use that value to do a post request in restAssured
The JSON file has
{
"items": [
{
"item_ref": 241,
"price": 100
}
]
}
jsonbody below is a String of the above JSON file
This is the code that fails:
JSONObject jObject = new JSONObject(jsonbody);
jObject.remove("item_ref");
jObject.put("item_ref","251");
System.out.println(jObject);
This is what I am getting:
{"item_ref":"251","items":[{"item_ref":241,"price":100}]}
What I want is {"items":[{"item_ref":251,"price":100}]}
I also tried
JSONObject jObject = new JSONObject(jsonbody);
jObject.getJSONObject("items").remove("item_ref");
jObject.getJSONObject("items").put("item_ref","251");
System
But it says JSONObject["items"] is not a JSONObject.
All I need is to replace the 241 with 251. Is there an easier way to do this?
In general if we have a predefined JSON body file and if we want to replace some of the values in the body and use that in our POST calls within RestAssured, is there any easier way to do it?
The problem is - field item_ref and price are not in JSON Object as you think they are.
They are in JSON Array which contains JSON Objects. In order to modify that value, you have to get elements of the array and THEN execute very similar code you wrote.
Check this out:
JSONObject jObject = new JSONObject(jsonbody);
JSONArray array = jObject.getJSONArray("items");
JSONObject itemObject = (JSONObject) array.get(0); //here we get first JSON Object in the JSON Array
itemObject.remove("item_ref");
itemObject.put("item_ref", 251);
The output is:
{"items":[{"item_ref":251,"price":100}]}
Also, you can create a Hashmap:
HashMap<String,String> map = new HashMap<>();
map.put("key", "value");
RestAssured.baseURI = BASE_URL;
RequestSpecification request = RestAssured.given();
request.auth().preemptive().basic("Username", "Password").body(map).put("url");
System.out.println("The value of the field after change is: " + map.get("key"));

Extract data from javascript

have a java script element , which when printed, gives [object Object].
console.log(data)
When i tried to JSON.Stringify(data) -it gives a json value:
{"key":"value"}
How to extract the value from the above object ?
JSON.stringify creates a JSON string representation of that JS object. If you want to use it as a JSON, you'd have to parse it again:
let data = '{"key": "value"}';
let dataJSON = JSON.parse(data);
console.log(dataJSON.key);
Outputs: value

Why cant parse JSON from file?

We have empty JSON file
I want to write new JSON objects in this file, and get from it Array of JSON objects (and after simply append new JSONs to array by 'push')
I write to the file incoming JSON object:
fs.writeFileSync(tasks, updatedJsonStr, encoding='utf8');
where
updatedJsonStr = JSON.stringify({"isCompleted":false,"task":"dfgdfg","date":"25.06.2015"});
So in the file we see added object.
After we get from the file our JSON objects:
tasksJsonObj = JSON.parse(fs.readFileSync("tasks.json", "utf-8"));
Append new JSON object as string and write it again:
updatedJsonStr = JSON.stringify(tasksJsonObj) + ',' + JSON.stringify(newJsonTask);
fs.writeFileSync(tasks, updatedJsonStr, encoding='utf8');
So we see 2 JSON objects in the file.
!But when I try to read file with 2 JSON objects - I got an error when reading JSON from the file ([SyntaxError: Unexpected token ,]):
try{
tasksJsonObj = JSON.parse(fs.readFileSync(tasks, "utf-8"));
console.log('aaaaa' + JSON.stringify(tasksJsonObj));
return true;
}catch (err) {
console.log("its not ok!");
console.log(err);
return false;
}
Your JSON formation is wrong,
{"isCompleted":false,"task":"dfgdfg","date":"25.06.2015"}, {"newisCompleted":false,"task":"dfgdfg","date":"25.06.2015"}
this is what you will get after concat two JSON stringify, which is also invalid.
Your JSON should be like this
[ {"isCompleted":false,"task":"dfgdfg","date":"25.06.2015"}, {"newisCompleted":false,"task":"dfgdfg","date":"25.06.2015"} ]
for that you can do something like this
var tasks = [];
tasks.push( {"isCompleted":false,"task":"dfgdfg","date":"25.06.2015"}) );
so your update jsonstr would be
updatedJsonStr = JSON.stringify( tasks );
again if you want to append a new json string, you can do like this
tasksJsonObj = JSON.parse(fs.readFileSync("tasks.json", "utf-8"));
tasksJsonObj.push( newJsonTask );
and then stringify it and write it back to file.
If you are trying to "extend" the object:
https://lodash.com/docs#assign
deep extend (like jQuery's) for nodeJS
If you are trying to "push" new objects into an array, then you're almost there:
var updatedJsonStr = JSON.stringify([{"isCompleted":false,"task":"dfgdfg","date":"25.06.2015"}]);
fs.writeFileSync(tasks, updatedJsonStr, encoding='utf8');
var tasksJsonArr = JSON.parse(fs.readFileSync("tasks.json", "utf-8"));
tasksJsonArr.push(newJsonTask);
There's a little problem with what you are writing. If you want to have multiple JSONs next to each other, you should consider putting them into an array:
updatedJsonStr = [];
updatedJsonStr.push(JSON.stringify(tasksJsonObj));
updatedJsonStr.push(JSON.stringify(newJsonTask));
and then write them into file!

Generate a JSON object form a the value of another JSON in WP8

I am working on a WP8 app. In this I need to connect to web services whose results will be some JSON. I was trying to extract some data from the result that the web service provide. I was able to extract from the initial JSON response. But I need to get some data from the value of one such key . SO I tried to generate another Json object from it. But I m stuck. please help.Please find my example code below(I am using Newtonsoft.JSon).
private void messages_buttons_Click(object sender, RoutedEventArgs e)
{
var str = "{'status': '0', 'result': '%7B%22campaign_id%22%3A%221%22%2C%22tfn%22%3A%2218773374136%22%2C%22campaign_code%22%3A%22PJC%22%2C%22ad_id%22%3A%221%22%2C%22qr_url%22%3A%22http%3A%5C%2F%5C%2F1d1.us%5C%2FPJC%5C%2F%22%2C%22campaign_name%22%3A%22PJ+Test+Campaign%22%2C%22is_active%22%3A%221%22%2C%22expire_on%22%3A%222021-05-05+00%3A00%3A00%22%2C%22start_on%22%3A%222021-05-05+00%3A00%3A00%22%2C%22alias%22%3A%22%22%2C%22icon_image_url%22%3A%22products%5C%2Fpjc%5C%2Fpjc3.jpg%22%2C%22fb_page_url%22%3A%22https%3A%5C%2F%5C%2Fwww.facebook.com%5C%2FJackLaLannePowerJuicerssfb%22%2C%22video_url%22%3A%22http%3A%5C%2F%5C%2Fyoutube.com%5C%2Fembed%5C%2FyZPedpRA9r0%3Fshowinfo%3D0%26autoplay%3D1%26loop%3D1%26playlist%3DyZPedpRA9r0%22%2C%22url%22%3A%22https%3A%5C%2F%5C%2Fwww.facebook.com'}";
JObject ne = JObject.Parse(str);
var x= (ne.GetValue("result")).ToString();
var z = x.Replace("%", "");
JObject newest = JObject.Parse(z);
var y = newest.GetValue("campaign_id");
MessageBox.Show(y.ToString());
}
I get an exception at "JObject newest = JObject.Parse(z);" with the message
Unexpected character encountered while parsing number: m. Path '', line 1, position 6.
Am I doing it entirely wrong?
On a general note: can I convert a value from one Json to a another JSOn Itself? i.e if the value of one json key is a string with some key value pairs, can i make a json object on that string?
You can't actually just remove the % chars to get a valid value. You need to decode the string.
If you use this:
HttpUtility.UrlDecode(x);
You'll find your "result" is actually invalid JSON:
{"campaign_id":"1","tfn":"18773374136","campaign_code":"PJC","ad_id":"1","qr_url":"http://1d1.us/PJC/","campaign_name":"PJ
Test Campaign","is_active":"1","expire_on":"2021-05-05
00:00:00","start_on":"2021-05-05
00:00:00","alias":"","icon_image_url":"products/pjc/pjc3.jpg","fb_page_url":"https://www.facebook.com/JackLaLannePowerJuicerssfb","video_url":"http://youtube.com/embed/yZPedpRA9r0?showinfo=0&autoplay=1&loop=1&playlist=yZPedpRA9r0","url":"https://www.facebook.com
So hacking the value to make it valid JSON might work for you, by adding the missing "} at the end should turn your value in to valid JSON and allow you to parse it.
JObject newest = JObject.Parse(x + "\"}");
var y = newest.GetValue("campaign_id");
It doesn't appear that z is a valid json object at this point. It is only the value of result. Try something like JObject.Parse("'result':" + z);