Getting values from json array using an array of object and keys in Python - arrays

I'm a Python newbie and I'm trying to write a script to extract json keys by passing the keys dinamically, reading them from a csv.
First of all this is my first post and I'm sorry if my questions are banals and if the code is incomplete but it's just a pseudo code to understand the problem (I hope not to complicate it...)
The following partial code retrieves the values from three key (group, user and id or username) but I'd like to load the objects and key from a csv to make them dinamicals.
Input json
{
"fullname": "The Full Name",
"group": {
"user": {
"id": 1,
"username": "John Doe"
},
"location": {
"x": "1234567",
"y": "9876543"
}
},
"color": {
"code": "ffffff",
"type" : "plastic"
}
}
Python code...
...
url = urlopen(jsonFile)
data = json.loads(url.read())
id = (data["group"]["user"]["id"])
username = (data["group"]["user"]["username"])
...
File.csv loaded into an array. Each line contains one or more keys.
fullname;
group,user,id;
group,user,username;
group,location,x;
group,location,y;
color,code;
The questions are: can I use a variable containing the object or key to be extract?
And how can I specify how many keys there are in the keys array to put them into the data([ ][ ]...) using only one line?
Something like this pseudo code:
...
url = urlopen(jsonFile)
data = json.loads(url.read())
...
keys = line.split(',')
...
# using keys[] to identify the objects and keys
value = (data[keys[0]][keys[1]][keys[2]])
...
But the line value = (data[keys[0]][keys[1]][keys[2]]) should have the exact number of the keys per line read from the csv.
Or I must to make some "if" lines like these?:
...
if len(keys) == 3:
value = (data[keys[0]][keys[1]][keys[2]])
if len(keys) == 2:
value = (data[keys[0]][keys[1]])
...
Many thanks!

I'm not sure I completely understand your question, but I would suggest you to try and play with pandas. It might be as easy as this:
import pandas as pd
df = pd.read_json(<yourJsonFile>, orient='columns')
name = df.fullname[0]
group_user = df.group.user
group_location = df.group.location
color_type = df.color.type
color_code = df.color.code
(Where group_user and group_location will be python dictionaries).

Related

How to extract specific values from JSON response in Postman and concatenate

I need to be able to do the following in Postman
Parse through a JSON response
Retrieve specific values: some nested, some not
(optional) Concatenate the final result
I can currently perform 1 and I can accomplish 2 for one specific value with the help of this explanation link
What I can't do is retrieve two values. Below is the sample response I am working with
{
"part": "9FH74T00",
"summaries": [
{
"id": "A1AGQF32TR"
}
]
}
I was able to modify the JS from the link above to extract the nested id value
var response = JSON.parse(responseBody);
var ids = response.summaries.map(function(summary) {
return summary.id;
});
console.log(ids);
How can I expand on the JS to also retrieve the part value and ideally output that in the console as part = id or 9FH74T00 = A1AGQF32TR
#lucas-nguyen's seems a valid response/comment to what you propose. What is not well explained is the model. summaries is an array so would you get multiple ids? The fact that you use a map makes me thing there will be multiple ids.
part = id1,id2,id3
or
part = id1
part = id2
part = id3
I've created a sample request with your payload and two ids in summaries. I've console.log 3 approaches:
single part and single id
single part and ids in a list
single part and ids in tuples
So with the example response:
{
"part": "9FH74T00",
"summaries": [
{
"id": "A1AGQF32TR"
},
{
"id": "SECONDID"
}
]
}
You would get the following output:
Option 1:
9FH74T00 = A1AGQF32TR
Option 2, list of ids:
9FH74T00 = A1AGQF32TR,SECONDID
Option 3, list of ids:
9FH74T00 = A1AGQF32TR
9FH74T00 = SECONDID
If for some reason you can't open the example, this is my test tab:
const response = pm.response.json().data;
// Just concatenate single part and single id
console.log("\nOption 1:")
console.log(`${response.part} = ${response.summaries[0].id}`)
// Co
console.log("\nOption 2, list of ids:")
const ids = response.summaries.map( x => x.id)
console.log(`${response.part} = ${ids.join(",")}`)
console.log("\nOption 3, list of ids:")
ids.forEach( x => console.log(`${response.part} = ${x}`))

How to extract values out of a array using JSON Extractor in jmeter?

I want to extract below json and use values accordingly.
I/p JSON:-
{
"status": "Success",
"message": "User created successfully",
"id": [
131188,
131191
]
}
Here I want values of id field. I used JSON Extractor and gave expression as $.id which gives me [131188,131191] in a variable. Now I want to use individual values out of this array i.e. 131188 and 131191.
Any Idea how to do it?
Update : I don't want to use 2 JSON Extractors.
Just add [*] to your JSON path expression as below
$.id[*]
This will create a jmeter variable for each value.Note that you should use -1 in the match numbers field.
You could use a json extractor and a "JSR223 PostProcessor" with groovy language. An example:
import groovy.json.JsonSlurper
//String jsonString = vars.get("jsonFromExtractor")
String jsonString = '''
{
"status": "Success",
"message": "User created successfully",
"id": [
131188,
131191
]
}
'''
log.info("jsonString:" + jsonString)
def json = new JsonSlurper().parseText( jsonString )
String idValue1 = json.get("id").get(0)
String idValue2 = json.get("id").get(1)
log.info("idValue1:" + idValue1)
log.info("idValue2:" + idValue2)
I hope this helps

How to print only some specific numbers in with JSON ,SWIFT?

1.I have this array and i want to extract only the "rate" values.
I want y Array to look like this
array = [6,355.1675 , 4,826.3112 , 5,429.8488]
[{
code = USD;
description = "United States Dollar";
rate = "6,355.1675";
"rate_float" = "6355.1675";
symbol = "$";
}, {
code = GBP;
description = "British Pound Sterling";
rate = "4,826.3112";
"rate_float" = "4826.3112";
symbol = "£";
}, {
code = EUR;
description = Euro;
rate = "5,429.8488";
"rate_float" = "5429.8488";
symbol = "€";
}]
It looks like you have JSON that contains an array of dictionaries.
Write some code that:
Decodes the JSON into native objects. At the simplest it would be converted to an array of dictionaries.
You could then write code that loops through the array, extracts the rate value for each array entry, and prints it.
As others have said, you could do this with a map statement, but if you're new to programming then the for loop approach is easier to understand.
If you array is called array, then you can do it this way:
array.map { print ($0["rate"] }

How can I sort based on children?

Using Vapor and Fluent (PostgreSQL if that matters) I have entity B that has aID: Node (A is B's parent) to reference A and A has a one-to-many relationship with B. How can I make a query to fetch all A's sorted by the count of B's?
I want the result to look something like this:
All A's in DB
[
{
"id": 4,
"name": "Hi",
"bCount": 1000
},
{
"id": 3,
"name": "Another",
"bCount": 800
},
{
"id": 5,
"name": "Test",
"bCount": 30
}
]
Firstly,
Create a modal for A
Turn that JSON string to array of A
if you do this your sorting becomes as easy as -
array.sort { $0.bCount < $1.bCount }
This is going to be tricky to implement entirely in Fluent using Entity. Firstly, you will need to use raw SQL to get your bCount. Secondly, you will need to change your init(node:) to accept bCount, though it shouldn't be in your makeNode() because we don't want to create a stored database field for it.
Try this for your raw SQL (untested):
SELECT
A.*,
(
SELECT COUNT(*)
FROM B
WHERE B.aID = A.id
) AS bCount
FROM A
ORDER BY bCount
Then, run that query to get your A models.
var models: [A] = []
if let driver = drop.database?.driver as? PostgreSQLDriver {
if case .array(let array) = try driver.raw(sql) {
for result in array {
do {
var model = try A(node: result)
models.append(model)
}
}
}
}
As I said before, your init method on A will be receiving bCount so you will need to store it there.

Json creation in ruby for a list

I am new to Ruby.
I want to create a JSON file for a group of elements.
For this, I am using eachfunction to retrieve the datas. I want to create json as follows for the 4 length array,
'{
"desc":{
"1":"1st Value",
"2":"2nd value"
"3":"3rd Value",
"4":"4th value"
},
}'
This is my array iteration,
REXML::XPath.each( doc, "//time" ) { |element1|
puts element1.get_text
}
I know here is the simple code to generate a JSON,
require 'json/add/core'
class Item < Struct.new(:id, :name); end
chair = Item.new(1, 'chair')
puts JSON.pretty_generate(chair)
This syntax will generate a json as follows,
{
"json_class": "Item",
"v": [
1,
"chair"
]
}
But I'm not sure how to do that to make JSON for my elements as stated above. Google search didn't give me a proper way to do this.
Can anyone help me here?
it means this?:
require 'json'
my_arr= ["1st Value","2nd Value","3rd Value","4th Value"]
tmp_str= {}
tmp_str["desc"] = {}
my_arr.each do |x|
tmp_str["desc"]["#{x[0]}"] = x
end
puts JSON.generate(tmp_str)
you can iterate the string array ,then take the strings to hash object.JSON can easy to parse Hash objcect .

Resources