I have the following json string and need to extract each of the survey_id values as a list. ie 74448500, 74052991, 65442357
{
"status":0,
"data":{
"surveys":[
{
"survey_id":"74448500"
},
{
"survey_id":"74052991"
},
{
"survey_id":"65442357"
}
],
"page":1,
"page_size":1000,
"metadata":{
"collaboration":{
"shared_by_total":0,
"unfiled_owned_total":143,
"shared_with_total":0,
"owned_total":242
}
}
}
}
Not sure what version of ColdFusion you are on, here are two possible ways to do it:
<cfscript>
x = deserializeJSON('{"status":0,"data":{"surveys":[{"survey_id":"74448500"},{"survey_id":"74052991"},{"survey_id":"65442357"}],"page":1,"page_size":1000,"metadata":{"collaboration":{"shared_by_total":0,"unfiled_owned_total":143,"shared_with_total":0,"owned_total":242}}}}');
// ColdFusion 11
y = x.data.surveys.map(function(item){
return item.survey_id;
});
writeDump(arrayToList(y));
// ColdFusion 9+
z = [];
for (item in x.data.surveys) {
arrayAppend(z, item.survey_id);
}
writeDump(arrayToList(z));
</cfscript>
Related
in this json file I want to get original_ur but when i cant get it , can some one help me how to get it please
{
"orders": {
"order_items":[
{
"product_min":{
"colors":[
{
"media":[
{
"original_url": b
"https://royalpetiq.com/royalpet2/public//storage/10628/msg5212971698-890.jpg",
}
]
}
]
}
}
]
}
}
go on quicktype id site and create model from this json after just creat object of that claass and parse this json response and after that you can get valu like
x.orders.order_items[0].product_min.colors[0].media[0].original_url
here is your json path
x.orders.order_items[0].product_min.colors[0].media[0].original_url
try {
var json = """{
"orders": {
"order_items":[
{
"product_min":{
"colors":[
{
"media":[
{
"original_url": "https://royalpetiq.com/royalpet2/public//storage/10628/msg5212971698-890.jpg"
}
]
}
]
}
}
]
}
}""";
var data = jsonDecode(json);
var url = data["orders"]["order_items"][0]["product_min"]["colors"][0]
["media"][0]["original_url"];
print("Url: $url");
} catch (e) {
print(e);
}
I think your json should be like that.
Here the url has a b at the beginning and a comma after the url which is not the correct syntax for json
Hope anybody could guide me here. I spend some hours on it and can't understand what's going on.
Mission: Replace a json element by a jsonpath search tag. (sort of $ref feature)
In my code example below i want to replace the value of DataReaderUser by a value found by the json path search $.UsersAndGroups.Users[?(#.Name == 'OMDASAccountUser')].Username . In this case it should result in the value "contoso\SVCSCOM-DO-OMDAS"
The code below works as expected.. the issue is below this code ..
https://dotnetfiddle.net/gEjggK
using System;
using Newtonsoft.Json.Linq;
public class Program
{
public static void Main()
{
string json = #"{
""SQLServer"": {
""SQLReportingServices"": {
""AccountSettings"": {
""DataReaderUser"": {""$JsonPath"": ""$.UsersAndGroups.Users[?(#.Name == 'OMDASAccountUser')].Username""},
}
}
},
""UsersAndGroups"": {
""Users"": [
{
""Name"": ""OMActionAccountUser"",
""Username"": ""contoso\\SVCSCOM-DO-OMDAS"",
},
{
""Name"": ""OMDASAccountUser"",
""Username"": ""contoso\\SVCSCOM-DO-OMDAS"",
}
]
}
}";
JObject jo = JObject.Parse(json);
var JsonPath = jo.SelectToken("..$JsonPath");
JsonPath.Parent.Parent.Replace(jo.SelectToken(JsonPath.ToString()));
Console.WriteLine(jo.ToString());
}
}
The output will be :
{
"SQLServer": {
"SQLReportingServices": {
"AccountSettings": {
"DataReaderUser": "contoso\\SVCSCOM-DO-OMDAS"
}
}
},
"UsersAndGroups": {
"Users": [
{
"Name": "OMActionAccountUser",
"Username": "contoso\\SVCSCOM-DO-OMDAS"
},
{
"Name": "OMDASAccountUser",
"Username": "contoso\\SVCSCOM-DO-OMDAS"
}
]
}
}
Now the issue:
I want to do the same for all possible jsonpaths refers. So i use the SelectTokens and an foreach . But it looks like the behavior is different , the parents are null.
https://dotnetfiddle.net/lZW3XP
using System;
using Newtonsoft.Json.Linq;
public class Program
{
public static void Main()
{
string json = #"{
""SQLServer"": {
""SQLReportingServices"": {
""AccountSettings"": {
""DataReaderUser"": {""$JsonPath"": ""$.UsersAndGroups.Users[?(#.Name == 'OMDASAccountUser')].Username""},
}
}
},
""UsersAndGroups"": {
""Users"": [
{
""Name"": ""OMActionAccountUser"",
""Username"": ""contoso\\SVCSCOM-DO-OMDAS"",
},
{
""Name"": ""OMDASAccountUser"",
""Username"": ""contoso\\SVCSCOM-DO-OMDAS"",
}
]
}
}";
JObject jo = JObject.Parse(json);
var JsonPaths = jo.SelectTokens("..$JsonPath");
foreach (var JsonPath in JsonPaths )
{
JsonPath.Parent.Parent.Replace(jo.SelectToken(JsonPath.ToString()));
}
Console.WriteLine(jo.ToString());
}
}
And the output:
Run-time exception (line 34): Object reference not set to an instance of an object.
Stack Trace:
[System.NullReferenceException: Object reference not set to an instance of an object.]
at Newtonsoft.Json.Linq.JsonPath.PathFilter.GetNextScanValue(JToken originalParent, JToken container, JToken value)
at Newtonsoft.Json.Linq.JsonPath.ScanFilter.<ExecuteFilter>d__4.MoveNext()
at Program.Main() :line 34
would be great to get some directions since i am spinning my head here.
michel
SelectTokens uses lazy evaluation and if you modify the token while enumerating all matches it can break in unexpected ways. A simple fix is to add ToArray() to force eager evaluation:
var JsonPaths = jo.SelectTokens("..$JsonPath").ToArray();
I have a mongo collection where documents have aprox the following structure:
item{
data{"emailBody":
"{\"uniqueKey\":\" this is a stringified json\"}"
}
}
What I want to do is to use 'uniqueKey' as an indexed field, to make an "inner join" equivalant with items in a different collection.
I was thinking about running a loop on all the documents -> parsing the json -> Saving them as new property called "parsedEmailBody".
Is there a better way to handle stringified json in mongo?
The only way is to loop through the collection, parse the field to JSON and update the document in the loop:
db.collection.find({ "item.data.emailBody": { "$type": 2 } })
.snapshot().forEach(function(doc){
parsedEmailBody = JSON.parse(doc.item.data.emailBody);
printjson(parsedEmailBody);
db.collection.updateOne(
{ "_id": doc._id },
{ "$set": { "item.data.parsedEmailBody": parsedEmailBody } }
);
});
For large collections, leverage the updates using the Bulk API:
var cursor = db.collection.find({ "item.data.emailBody": { "$type": 2 } }).snapshot(),
ops = [];
cursor.forEach(function(doc){
var parsedEmailBody = JSON.parse(doc.item.data.emailBody);
ops.push({
"updateOne": {
"filter": { "_id": doc._id },
"update": { "$set": { "item.data.parsedEmailBody": parsedEmailBody } }
}
});
if (ops.length === 500) {
db.collection.bulkWrite(ops);
ops = [];
}
});
if (ops.length > 0) { db.collection.bulkWrite(ops); }
I've looked and can't find anything and this is really starting to annoy me...
I've got JSON.Net and the following snippet of code
var x = insList.Select(a => new
{
ac = a.CreatedDate,
bd = a.CreatedBy
});
this.Context.Response.Write(x.ToJSON());
.ToJSON() is a simple extension method:
public static string ToJSON(this object obj)
{ return JsonConvert.SerializeObject(obj); }
The json output is
Ideally what I'd like is the highlight bits to have the same root name, rather than just {}
Can anyone help please?
Objects do not have names in JSON, properties do. (See JSON.org.) Therefore, if you want to name an object, you'll have to make it the value of a property of another containing object.
var x = insList.Select(a => new
{
rootName = new
{
ac = a.CreatedDate,
bd = a.CreatedBy
}
});
This will yield the following JSON:
[
{
"rootName": {
"ac": "0001-01-01T00:00:00",
"bd": 0
}
},
{
"rootName": {
"ac": "0001-01-01T00:00:00",
"bd": 0
}
},
{
"rootName": {
"ac": "0001-01-01T00:00:00",
"bd": 0
}
}
]
JSON structure:
{
"codes":[
{
"id":"1",
"code":{
"fname":"S",
"lname":"K",
"dateofbirth":{
"month":"12",
"day":"02",
"year":"1998"
}
}
},
{
"id":"2",
"code":{
"fname":"M",
"lname":"D",
"dateofbirth":{
"month":"10",
"day":"02",
"year":"1998"
}
}
}
]
}
I want to loop through each code AND dateofbirth and alert if the month is 12. If the month is not 12, then do nothing.
success: function(data){
var x;
for (x = 0; x < data.codes.length; x++){
var count=0;
for (property in data.codes[x].code) {
count++;
}
}
}
How can I loop through dateofbirth and check for the value of month?
Example of JSON structure with more than 1 property under 'code' that can be an object. So I want to loop through all the properties within code and check for the value of the month property instead of manually checking for a particular property.
{
"codes":[
{
"id":"1",
"code":{
"fname":"S",
"lname":"K",
"dateofbirth":{
"month":"12",
"day":"02",
"year":"1998"
},
"membership":{
"month":"12",
"day":"12",
"year":"2011"
}
}
},
{
"id":"2",
"code":{
"fname":"M",
"lname":"D",
"dateofbirth":{
"month":"10",
"day":"02",
"year":"1998"
},
"membership":{
"month":"10",
"day":"12",
"year":"2011"
}
}
}
]
}
mycodes=// the object from parsed JSON
for (i=0; i<mycodes.codes.length; i++) {
if (mycodes.codes[i].code.dateofbirth.month=="12") {
alert("Code " + mycodes.codes[i].id + " has birth month of 12");
}
}
BTW, you really should store birthdates as numbers, not strings.