Validate JSON response with array values - json

I have a JSON response as shown below (in array values). I want to validate whether the Keys (attributes) are properly retrieved in the Response. I would like to compare a list of expected values against the response values (only the first set of array values)
Eg:
"participants": [
{
"FirstName": "Kim",
"LastName": "Hykes",
"Street1": "ABC",
"Street2": "ABCD",
"City": "city1",
"State": "NJ"
}
{
"FirstName": "John",
"LastName": "David",
"Street1": "XYZ",
"Street2": "UXYZ",
"City": "city2",
"State": "NY"
}
]
Using JSONparser, the above JSON is parsed and the result will be:
participants[0].FirstName, participants[0].LastName,
participants[0].Street1, participants[0].Street2, participants[0].City,
participants[0].State, participants[1].FirstName,
participants[1].LastName,
participants[1].Street1, participants[1].Street2, participants[1].City,
participants[1].State
And it goes on until 50 participants
I would like to see whether all the required Keys are fetched from the database and would like to check only the first Array fields i.e. only in Participants[0].
Can anyone help me to figure the solution here?

Do you mean something like this, to validate whether the keys are in there, and in the correct order?
var response = {"participants": [
{
"FirstName": "Kim",
"LastName": "Hykes",
"Street1": "ABC",
"Street2": "ABCD",
"City": "city1",
"State": "NJ"
},
{
"FirstName": "John",
"LastName": "David",
"Street1": "XYZ",
"Street2": "UXYZ",
"City": "city2",
"State": "NY"
}
]
}
var keysNeeded = ['FirstName', 'LastName', 'Street1', 'Street2', 'City', 'State']
var i = 0;
for (key in response.participants[0]) {
if (key == keysNeeded[i]) {
console.log('all is OK with key '+key)
}
i++;
}

Related

Need to find key-value pair and replace key-value pair in JSON using JQ

I have this JSON
{
"firstName": "Rajesh",
"lastName": "Kumar",
"gender": "man",
"age": 24,
"address": {
"streetAddress": "126 Udhna",
"city": "Surat",
"state": "WB",
"postalCode": "394221"
},
"phoneNumbers": [
{
"type": "home",
"number": "7383627627"
}
]
}
I need to find the value of the "state" key Using JQ and replace the value in JSON. I do not want to fetch it by providing the position of the key, Like
firstName=$(cat sample-json.json | jq -r '.firstName')
My expected output
{
"firstName": "Rajesh",
"lastName": "Kumar",
"gender": "man",
"age": 24,
"address": {
"streetAddress": "126 Udhna",
"city": "Surat",
"state": "Bihar",
"postalCode": "394221"
},
"phoneNumbers": [
{
"type": "home",
"number": "7383627627"
}
]
}
If you're willing to specify .address:
jq '.address.state = "Bihar"' sample-json.json
Otherwise:
jq 'walk(if type == "object" and has("state") then .state = "Bihar" else . end)' sample-json.json
This last will replace all .state values. If you only want to replace the first occurrence:
jq 'first(..|objects|select(has("state"))).state = "Bihar"' sample-json.json
And so on. It would really help all concerned if you could make the requirements clear.

convert JSON from one key value pair to another

I want to generate new JSON from the existing, but I am not able to do so.
Given JSON:
[
{
"id": "1",
"firstName": "john",
"lastName": "doe"
},
{
"id": "2",
"firstName": "michal",
"lastName": "foo"
},
{
"id": "3",
"firstName": "john",
"lastName": "smith"
}
]
want to convert it to:
[
{
"id": "1",
"firstName": "john-doe"
},
{
"id": "2",
"firstName": "michal"
},
{
"id": "3",
"name": "john-smith"
}
]
I want only id name, but want lastName when only the firstName is same.
So, I am not able to do this condition of merging name, and add surname only when firstName is same
Please try to mention the following in your question:
Technologies you are using
What you are trying to do/build
Code you have already tried to write
Errors (if any)

Python json.loads() returns list instead of dict

I have the following json from a API i'm getting via requests.get().
Now I want to turn this json into a dict with json.loads() but the outcome is a list.
From https://www.w3schools.com/python/python_json.asp the outcome should be a dict... or am I wrong here? Thanks!
import requests
import json
r = requests.get('http://url/api,
auth=requests.auth.HTTPBasicAuth('user','pass'))
x = json.loads(r.text)
# type(x) >>> <class 'list'>
json:
[
{
"id": 400285,
"statusId": 1,
"deliveryAddress": {
"firstName": "Admin",
"lastName": "Admin",
"company": "Testshop 2",
"street": "Teststr. 1",
"houseNumber": "",
"additionalAddressInfo": "",
"postcode": "12345",
"city": "Testort",
"state": "Bremen",
"country": "Germany",
"countryIsoCode": "DE"
},
"billingAddress": {
"firstName": "Admin",
"lastName": "Admin",
}
},
{
"id": 400288,
"statusId": 1,
"deliveryAddress": {
"firstName": "Carolin",
"lastName": "Pr\u00f6ger",
"company": "",
"street": "teststra\u00dfe 12",
"houseNumber": "",
"additionalAddressInfo": "",
"postcode": "12345",
"city": "Bremen",
"state": "Bremen",
"country": "Germany",
"countryIsoCode": "DE"
},
"billingAddress": {
"firstName": "Carolin",
"lastName": "Pr\u00f6ger",
}
}
]
Edit1:
mydict= {}
for item in mylist:
mydict['ID'] = item['id']
mydict['statusID'] = item['statusId']
The data type returned from json.load is assigned depending of the data structure of the json file.
Your json file has [] (list structure).
But you need your json file to have {} (list structure).
It is because of your json response contains list not object.

How can i remove key's from json doc array in nodeJS

Is there a quick and stable way to remove all a key value pair from a json Doc array. In my case i have data returned from my DB which contains more fields then i want to show to user so i want to query my db and see what key's he is supposed to get before returning the json to client.
In this sample the data has 3 keys, FirstName,LastName and dob how would i go to remove all dob Key and values from the json, also if i have to remove more then one Key Value pair does it make difference when you do it ?
{
"result":[
{
"FirstName": "Test1",
"LastName": "User",
"dob": "01/01/2011"
},
{
"FirstName": "user",
"LastName": "user",
"dob": "01/01/2017"
},
{
"FirstName": "Ropbert",
"LastName": "Jones",
"dob": "01/01/2001"
},
{
"FirstName": "hitesh",
"LastName": "prajapti",
"dob": "01/01/2010"
}
]
}
You can use the delete operator on the obj while looping through your data.
let data = {
"result": [{
"FirstName": "Test1",
"LastName": "User",
"dob": "01/01/2011"
},
{
"FirstName": "user",
"LastName": "user",
"dob": "01/01/2017"
},
{
"FirstName": "Ropbert",
"LastName": "Jones",
"dob": "01/01/2001"
},
{
"FirstName": "hitesh",
"LastName": "prajapti",
"dob": "01/01/2010"
}
]
}
// #param keys: an array of keys to remove
function removeKeyValue(obj, keys) {
obj.forEach(currObj => {
keys.forEach(key => {
delete currObj[key];
});
});
}
removeKeyValue(data.result, ["dob", "LastName"]);
console.log(data.result);

Ways to store JSON data

I'm making an API call and the response I'm getting is a rather large JSON string. I'd like to minimise API calls to a) avoid hitting the rate limit and b) speed things up.
Here's an example of my JSON data:
{
"firstName": "John",
"lastName": "Smith",
"isAlive": true,
"age": 25,
"address": {
"streetAddress": "21 2nd Street",
"city": "New York",
"state": "NY",
"postalCode": "10021-3100"
},
"phoneNumbers": [
{
"type": "home",
"number": "212 555-1234"
},
{
"type": "office",
"number": "646 555-4567"
}
],
"children": [],
"spouse": null
}
My question:
What are my options with reference to persistent storage?
Please note: the API I'm using is in beta; so I'd like to avoid using MySQL for now because the JSON representation could change, resulting in my tables needing an overhaul.