I am using the library parson to construct JSON messages. I did not figure it out how to make sub-key without using the dotfonction. The JSON, I would like to make is :
"received_data": {
"X-YY": {
"pm10": 1,
"pm25": 2,
"pm100": 3
},
"X-ZZ": {
"pm10": 1,
...
}
}
From now I only found how to make the JSON Array to get "pm10,pm25,pm100" values by using this code :
//creating a sub Json_Array
JSON_Value *branch = json_value_init_array();
JSON_Array *leaves = json_value_get_array(branch);
//creating measurement Json
JSON_Value *leaf_value = json_value_init_object();
JSON_Object *leaf_object = json_value_get_object(leaf_value);
json_object_set_string(leaf_object,"PM10:",val);
json_object_set_string(leaf_object,"PM25:",val1);
json_object_set_string(leaf_object,"PM100:",val2);
json_array_append_value(leaves,leaf_value);
I don't really understand how to link the keys between them using the parson library ? Can someone help me figure it out ?
Related
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}`))
Example:
API A:
{
"customer":[
{
"name":"Jane",
"phone":"9999999",
"email":"jane#test.com"
},
{
"name":"John",
"phone":"8888888",
"email":"john#test.com"
},
{
"name":"Joe",
"phone":"7777777",
"email":"Joe#test.com"
}
]
}
Using the JSON extractor, I want to get the names of all the customers
so: Jane, John, Joe
How do I get these values and turn them into an array
[{"name":"Jane", "name":"John", "name":"Joe"}]
And pass it onto the next API?
Note: That it has to be dynamic so API A could show different 2 names or 1 name or more and needs to be adjusted into the array
First of all your [{"name":"Jane", "name":"John", "name":"Joe"}] is not a valid JSON, you can check it yourself:
so I strongly doubt that this is the string you need to generate.
So if you really need to construct this value you can do something like:
Add JSR223 PostProcessor as a child of the request which returns this "customers" data
Put the following code into "Script" area:
def response = new groovy.json.JsonSlurper().parse(prev.getResponseData())
def payload = new StringBuilder()
payload.append('[{')
0.upto(response.customer.size - 1, { index ->
payload.append('"name": "').append(response.customer[index].name).append('"')
if (index != response.customer.size - 1) {
payload.append(',')
}
})
payload.append('}]')
vars.put('payload', payload as String)
Refer the generated value as ${payload} where required
Demo:
More information:
JsonSlurper
Apache Groovy - Parsing and producing JSON
Apache Groovy - Why and How You Should Use It
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).
I have been following the instructions here:
https://www.codenameone.com/javadoc/com/codename1/io/JSONParser.html to retrieve a value from a json file.
I have managed to read the top level value of my json content - however I cannot see how to read the value of a nested tag e.g. using this file ...
{
"glossary":{
"title":"example glossary",
"GlossDiv":{
"title":"S",
"GlossList":{
"GlossEntry":{
"ID":"SGML",
"SortAs":"SGML",
"GlossTerm":"Standard Generalized Markup Language",
"Acronym":"SGML",
"Abbrev":"ISO 8879:1986",
"GlossDef":{
"para":"A meta-markup language, used to create markup languages such as DocBook.",
"GlossSeeAlso":[
"GML",
"XML"
]
},
"GlossSee":"markup"
}
}
}
}
}
Please can someone show me how to get to the value of "para" above?
Thanks
After parsing your json data based on this, you can use Result to read deep into the json content:
import com.codename1.processing.Result;
...
Map<String, Object> data = json.parseJSON(r);
Result result = Result.fromContent(data);
String id = result.getAsString("glossary/GlossDiv/GlossList/GlossEntry/ID");
String para = result.getAsString("glossary/GlossDiv/GlossList/GlossEntry/GlossDef/para");
I am using json parser lib written in C to parse JSON objects. The lib link is : https://github.com/udp/json-parser.
The json object/string, which I am trying to parse is :
{"video_id": 105, "st": "S3", "processing" : [{"start" : "1", "end" : "2"}]}}
"processing" contains another JSON object.
I have parsed the first three items. But I am not able to figure out a way to parse the "processing" json object. I am using following code:-
if (!strcmp(json->u.object.values[i].name, "video_id"))
{
video_id=json->u.object.values[i].value->u.integer;
}
.
.
if (!strcmp(json->u.object.values[i].name, "processing"))
{
printf("\nNumber of JSON OBJECTS : %d\n", json->u.object.values[i].value->u.object.length);
}
json is the parsed object obtained via calling the lib on the JSON string. Can anyone guide me how to handle the nested object ?
Any help will be really appreciated
My complete code is :
json_value *json;
json_char *json_object="{\"video_id\": 105, \"st\": \"S3\", \"processing\" : [{\"type\" : \"clipping\"},{\"fese\" : \"dipping\"}]}";
printf("%s",json_object);
//json_value * json_parse (const json_char * json,
// size_t length);
json=json_parse(json_object, strlen(json_object));
// json_type json_object;
printf("\n%s\n",json->u.object.values[0].name);
printf("\t%d\n",json->u.object.values[0].value->u.integer);
printf("\n%s\n",json->u.object.values[2].name);
printf("\t%d\n",json->u.object.values[2].value->u.object.length);
printf("\t%s\n",json->u.object.values[2].value->u.object.values[0].name);
From the documentation, API field::
The type field of json_value is one of:
json_object (see u.object.length, u.object.values[x].name, u.object.values[x].value)
json_array (see u.array.length, u.array.values)
json_integer (see u.integer)
json_double (see u.dbl)
json_string (see u.string.ptr, u.string.length)
json_boolean (see u.boolean)
json_null
So, check the type field of the "processing" value. If found to be json_array, do a json_parse for the array to get a new json_value. Now this json_value will provide you with the nested JSON objects.
Take these as reference:
js_v->u.object.values[1].value->u.array.values[0]->type
js_v->u.object.values[1].value->u.array.values[0]->u.string.ptr
I've used them to reference to a string element inside an array:
{"t":"type","d":["element1","element2","element3"]}
In your case, I think you should to repeat the structure like this:
js_v->u.object.values[2].value->u.array.values[0]->u.object.values[0]->u.string.ptr
luck!