simple json parsing with asp Xtreme - json

Just confused with one little thing.
I am currently getting { "data": [ { "response": "true" } ] } with the following code.
But I simple want to get { "response": "true" }.
I tried every way I can but I kept failing.
I will appreciate a lot if you can help me with it.
Set Dataset = JSON.parse("{ ""data"": [] }")
Set Record = JSON.parse("{}")
Record.set "response", "true"
Dataset.data.push(Record)
Set Record = nothing
Data = JSON.stringify(Dataset, null, 2)

Set Record = JSON.parse("{}")
Record.set "response", "true"
Data = JSON.stringify(Record, null, 2)
I assume that JSONObject.data.push adds the record to an unnamed array.

Related

Checking if a key exists in a nested JSON element using Newtonsoft JSON and VB.NET

Using Newtonsoft Json with VB.NET I am trying to read some nested keys/elements within a block of JSON.
The JSON looks like this and is held in string strSuppliedJSON:
{
"seller": {
"id": 123,
"name": "Seller Name",
"address1": "Seller address1",
"country": "Seller country"
},
"buyer": {
"id": 987,
"name": "Buyer name",
"address1": "Buyer address1",
"country": "Buyer country"
},
"interview": {
"call_id": 123,
"vin": "The vin from the machine section",
"call_date": "2019-12-31 23:59:59",
"questions": ["Question1", "Question2", "Question3", "Question5", "Question5"],
"triggers": [{
"question": "Question1",
"answers": ["Answer1", "Answer2"]
}]
}
}
Before reading the values I need to make sure some of the keys exist using ContainsKey.
The following works fine:
Imports Newtonsoft.Json
Imports Newtonsoft.Json.Linq
' Create a dictionary
Dim dictionary As IDictionary(Of String, JToken) = JObject.Parse(strSuppliedJSON)
' Check if key exists - interview:triggers
If JObject.Parse(dictionary("interview").ToString()).ContainsKey("triggers") = False Then
strAllChecksPassed = False
result = "ERROR: JSON element not found: interview:triggers"
End If
However, when trying to check or read the interview:triggers:question things are falling over.
Using this, fails:
' Check if key exists - interview:triggers
If JObject.Parse(dictionary("interview").ToString()).ContainsKey("triggers") = False Then
strAllChecksPassed = False
result = "ERROR: JSON element not found: interview:triggers"
Else
' interview:triggers DOES exist, now check if the question exists - interview:triggers:question
If JObject.Parse(dictionary("interview")("triggers").ToString()).ContainsKey("question") = False Then
strAllChecksPassed = False
result = "ERROR: JSON element not found: interview:triggers:question"
End If
End If
The line that throws the error is:
If JObject.Parse(dictionary("interview")("triggers").ToString()).ContainsKey("question") = False Then
And the error is:
Newtonsoft.Json.JsonReaderException: Error reading JObject from JsonReader. Current JsonReader item is not an object: StartArray. Path '', line 1, position 1
So I then tried to create a sub-dictionary of just the interview element.
I used this:
' Create a sub-dictionary of just the Interview element
Dim subDictionary As IDictionary(Of String, JToken) = JObject.Parse(dictionary("interview").ToString())
And if I then do Response.Write(subDictionary) I now see a smaller subset of my JSON, as expected:
{
"call_id": 123,
"vin": "The vin from the machine section",
"call_date": "2019-12-31 23:59:59",
"questions": ["Question1", "Question2", "Question3", "Question5", "Question5"],
"triggers": [{
"question": "Question1",
"answers": ["Answer1", "Answer2"]
}]
}
But then when trying to use my new subDictionary in the exact same way to see if the question key exists:
' Check if key exists - interview:triggers:question
If JObject.Parse(subDictionary("triggers").ToString()).ContainsKey("question") = False Then
strAllChecksPassed = False
result = "ERROR: JSON element not found: interview:triggers:question"
End If
I get the exact same error of:
Newtonsoft.Json.JsonReaderException: Error reading JObject from JsonReader. Current JsonReader item is not an object: StartArray. Path '', line 1, position 1
Even though the line of code is identical!
How do I check if the nested key interview:triggers:question exists in my JSON, and what its value is?
Look closely at "triggers" in the JSON: it's actually an array of objects, not an object. You need to index the array before you can access "question".
Also note that every time you call ToString, you're reserializing something that you just deserialized with Parse. You don't need to do that. Parse the JSON once into a JObject and then reuse that object.
My VB-fu isn't great; I wrote this in C# and then converted it but the critical part is Dim first As JToken = triggers(0). This gets the first array element, on which you can get the value associated with "question".
Dim suppliedObject As JObject = JObject.Parse(strSuppliedJSON)
Dim interview As JToken = suppliedObject("interview")
Dim triggers As JToken = If(interview IsNot Nothing, interview("triggers"), Nothing)
If triggers Is Nothing Then
strAllChecksPassed = False
result = "ERROR: JSON element not found: interview:triggers"
Else
Dim first As JToken = triggers(0)
Dim question As JToken = If(first IsNot Nothing, first("question"), Nothing)
If question Is Nothing Then
strAllChecksPassed = False
result = "ERROR: JSON element not found: interview:triggers:question"
End If
End If
It fails because your path is not proper.
[] is an Array. You write out the name for single items (within {}), for arrays you write index (number).
And why are you parsing multiple times? Use what you already have, for example:
Dim JsonResp As JObject = JObject.Parse(<JSON>)
'Now there's multiple ways to do the same, here's one
If JsonResp ("interview")("triggers")(0)("question") Is Nothing Then
strAllChecksPassed = False
result = "ERROR: JSON element not found: interview:triggers:question"
End If

Extracting one specific line from parsed JSON string

Trying to pull first value from a parsed JSON string using the JsonConverter library.
What I currently have is:
result = objHTTP.responseText
Set parsedResult = JsonConverter.ParseJson(result)
i = 3
For Each Item In parsedResult("From")
wsSheet0.Cells(i, 12) = parsedResult("From")(Item)("Price")
i = i + 1
Next
With parsedResult("From")
wsSheet0.Cells(11, 12) = parsedResult("From")("Chocolate")("Price")("AsAtDate")
End With
The last line of this gets a type mismatch error, so I'm still trying to figure out how to just pull that one line item.
For the sake of clarity, the parsed JSON string looks like:
{
"From":{
"Chocolate":{
"Price":1.0,
"AsAtDate":"2018-05-04T00:00:00"
},
"Lime":{
"Price":1.35415115,
"AsAtDate":"2018-05-04T00:00:00"
},
"Strawberry":{
"Price":1.19517151,
"AsAtDate":"2018-05-04T00:00:00"
},
"Vanilla":{
"Price":0.77522986,
"AsAtDate":"2018-05-04T00:00:00"
},
"Blueberry":{
"Price":1.00084071,
"AsAtDate":"2018-05-04T00:00:00"
},
"Lemon":{
"Price":0.75030012,
"AsAtDate":"2018-05-04T00:00:00"
}
},
"To":"Chocolate",
"RequestedDate":"2018-05-22T08:26:16"
}
Use
parsedResult("From")("Chocolate")("AsAtDate")
Or more generally to get all:
parsedResult("From")(item)("AsAtDate")

Parsing json : Test is json key existing

I'm request with API REST a JIRA filter since Excel and I return my result in a json object.
I'm parsing this object and I Try to show my result (in a msgbox for now) but I have a problem when the json Key doesn't exist !
A extract of my json :
{
"expand":"schema,names",
"startAt":0,
"maxResults":500,
"total":2,
"issues":[
{
"expand":"operations,versionedRepresentations,editmeta,changelog,renderedFields",
"id":"00001",
"fields":{
"components":[
{
"id":"01",
"name":"component_1"
},
{
"id":"02",
"name":"component_02"
}
]
}
},
{
"expand":"operations,versionedRepresentations,editmeta,changelog,renderedFields",
"id":"00002",
"fields":{
"components":[
]
}
},
]
}
As you cans see, in my first issue (id 00001) I have a 2 components key but in my second issus (id 0002) I don't have component key, because this fields is empty in JIRA for this issue.
So, a part of my code to show my result :
For Each Item In jsonObject("issues")
issueId = Item("id")
compoId1 = Item("fields")("components")(1)("id")
compoId2 = Item("fields")("components")(2)("id")
i = i + 1
'PRINT_OF_MY_RESULT
Next
My problem :
If my issue (00001) has a "component" value, it's OK and I can return my result but ... if my issus (00002) hasn't a result, my code failled to define compoId ... and my code crash.
Did you have a simple solution ? I try somethings with Exists, isEmpty, etc etc ... but nothing concluent for me :(
You can modify your solution some what like this,
For Each Item In jsonObject("issues")
issueId = Item("id")
For Each componentItem In jsonObject(Item("fields")("components"))
If componentItem("id")==1 then
compoId1 = componentItem("id")
EndIf
If componentItem("id")==1 then
compoId2 = componentItem("id")
EndIf
Next
i = i + 1
'PRINT_OF_MY_RESULT
Next

Parsing, Extracting & Returning JSON as Hash

I am trying to make a localized version of this app: SMS Broadcast Ruby App
I have been able to get the JSON data from a local file & sanitize the number as well as open the JSON data. However I have been unable to extract the values and pair them as a scrubbed hash. Here's what I have so far.
def data_from_spreadsheet
file = open(spreadsheet_url).read
JSON.parse(file)
end
def contacts_from_spreadsheet
contacts = {}
data_from_spreadsheet.each do |entry|
puts entry['name']['number']
contacts[sanitize(number)] = name
end
contacts
end
Here's the JSON data sample I'm working with.
[
{
"name": "Michael",
"number": 9045555555
},
{
"name": "Natalie",
"number": 7865555555
}
]
Here's how I would like the JSON to be expressed after the contacts_from_spreadsheet method.
{
'19045555555' => 'Michael',
'19045555555' => 'Natalie'
}
Any help would be much appreciated.
You could create array of pairs (hashes) using map and then call reduce to get a single hash.
data = [{
"name": "Michael",
"number": 9045555555
},
{
"name": "Natalie",
"number": 7865555555
}]
data.map{|e| {e[:number] => e[:name]}}.reduce Hash.new, :merge
Result: {9045555555=>"Michael", 7865555555=>"Natalie"}
You don't seem to have number or name extracted in any way. I think first you'll need to update your code to get those details.
i.e. If entry is a JSON object (or rather was before parsing), you can do the following:
def contacts_from_spreadsheet
contacts = {}
data_from_spreadsheet.each do |entry|
contacts[sanitize(entry['number'])] = entry['name']
end
contacts
end
Not really keeping this function within JSON, but I have solved the problem. Here's what I used.
def data_from_spreadsheet
file = open(spreadsheet_url).read
YAML.load(file)
end
def contacts_from_spreadsheet
contacts = {}
data_from_spreadsheet.each do |entry|
name = entry['name']
number = entry['phone_number'].to_s
contacts[sanitize(number)] = name
end
contacts
end
This returned back clean array here:
{"+19045555555"=>"Michael", "+17865555555"=>"Natalie"}
Thanks everyone who added input!

Specify field projections in spring mongo db query

{
"_id":"1",
"company":"ABCD",
"Address":{
"Location":"XYZ"
},
"empName":[{
"ID":1,
"Name":"test1"
},
"ID":2,
"Name":"test2"
},
"ID":3,
"Name":"test3"
}]
}
am using mongoTemplate query,
Criteria findCriteria1 = Criteria.where("_id").is("1");
Criteria find2Criteria = Criteria.where("empName").elemMatch(Criteria.where("ID").is(1));
BasicQuery basicQuery = new BasicQuery(findCriteria1.getCriteriaObject(), find2Criteria.getCriteriaObject());
mongoTemplate.findOne(basicQuery, ClassName.class);
but my result as below with other fields displayed null.
{
"_id":"1",
"company":null,
"Address":null,
"empName":[{
"ID":1,
"Name":"test1"
}]
}
my expected result should be like this,
"_id":"1",
"company":"ABCD",
"Address":{
"Location":"XYZ"
},
"empName":[{
"ID":1,
"Name":"test1"
}]
Can you please help me to fix this issue.
Thanks in advance,
You can use below code.
You can chain the fields you require in the Field class.
Criteria criteria = Criteria.where("_id").is("1");
Query query = new Query(criteria);
query.fields().elemMatch("empName", Criteria.where("ID").is(1)).include("company");
mongoTemplate.findOne(query , ClassName.class);
Do Read the documentation for Criteria and BasicQuery.
The second argument in this
BasicQuery basicQuery = new BasicQuery(findCriteria1.getCriteriaObject(), find2Criteria.getCriteriaObject());
is basically a projection. i.e. you are telling the driver to fetch only the fields mentioned in those. Hence other fields are not fetched and hence null.
If you want to fetch all fields this is what you should do in your case
Criteria findCriteria1 = Criteria.where("_id").is("1");
Criteria find2Criteria = Criteria.where("empName").elemMatch(Criteria.where("ID").is(1));
BasicQuery basicQuery = new BasicQuery(findCriteria1.andOperator(find2Criteria).getCriteriaObject());