Can't iterate through JSON object - json

I'm pulling a JSON request from the politifact API:
request('http://politifact.com/api/v/2/statement/?format=[JSON]&order_by=-ruling_date&limit=1')
.then(({
data
}) => {
newArticles = extractListingsFromJSON(data);
and parsing it with a function that the JSON is passed to
function extractListingsFromJSON(json) {
var jsonObject = json.objects
Outputs entire objects array
var headline = jsonObject[0].facebook_headline
console.log("headline:\n" + headline)
Outputs headline from Objects[0]
This works as intended. However, when I try to iterate through the objects array like so:
for (var attr in jsonObject) {
console.log(attr+": "+jsonObject.facebook_headline);
}
Outputs "0: undefined"
I also tried:
console.log(attr+": "+jsonObject[facebook_headline];
Outputs nothing

As you mentioned yourself jsonObject is an array.
json.objects.forEach(function (i) {
console.log(i.facebook_headline)
})

You still need the attr key to iterate through the jsonObject. Try doing attr+" :"+jsonObject[attr].facebook_headline
instead.

Related

How to remove list square brackets from serialized json string

I'm calling a stored procedure using a controller.
var insert_query = entities.Database.SqlQuery<Call_Info>("exec [dbo].[insert_call_info] #call_id",
new SqlParameter("call_id", call_id)).ToList();
jsonResult = JsonConvert.SerializeObject(insert_query); // <-- using Newtonsoft.Json
The json string is the following:
"[{\"call_info_id\":18,\"call_id\":91389,\"user_id\":\"105bdbfb-d65a-42d3-ac79-c1e2575ed243\",\"call_arrive\":\"2020-04-03T21:51:24.797\",\"call_end\":\"2020-04-03T22:04:24.797\",\"info\":\"test\",\"AspNetUser\":null,\"Call\":null,\"StatusCode\":1}]"
Is there a way to remove the [ and ] brackets?
I want the json string to be:
{\"call_info_id\":18,\"call_id\":91389,\"user_id\":\"105bdbfb-d65a-42d3-ac79-c1e2575ed243\",\"call_arrive\":\"2020-04-03T21:51:24.797\",\"call_end\":\"2020-04-03T22:04:24.797\",\"info\":\"test\",\"AspNetUser\":null,\"Call\":null,\"StatusCode\":1}
var insert_query = entities.Database.SqlQuery<Call_Info>("exec [dbo].[insert_call_info] #call_id",
new SqlParameter("call_id", call_id)).ToList();
if(insert_query!=null && insert_query.Count()>0)
{
jsonResult = JsonConvert.SerializeObject(insert_query[0]);
}
This will serialise only 1st element so it wont have []

Deserialize Json Object list with id as root with jackson

I have this json structure from firebase where it's a list of objects but the root of each object is the ID
How can I serialize this to a list of object with the id/root as a member variable. This is for Spring boot so I would prefer if it were a Jackson2 solution.
This may be the same question as Jackson JSON key as value in Java but my answer is better because it doesn't require an extra/useless class
val reader = ObjectMapper().reader()
val tree = reader.readTree(testJson)
val eventList = mutableListOf<Event>()
tree.fields().iterator().forEach {
val event = Event(
it.key,
it.value.get("name").asText(),
it.value.get("description").asText(),
it.value.get("startDate").asText(),
it.value.get("startTime").asText(),
it.value.get("endDate").asText(),
it.value.get("endTime").asText(),
it.value.get("imageUrl").asText()
)
eventList.add(event)
}
I have found a solution using jackson in kotlin, it's not the prettiest but it works. the fields method returns a map of children. So, I am iterating through the map and adding the key as the object id member and then grabbing the rest of the data from the nested map.
Sorry, I am not a pro in Jackson. But there is a simple way to transform your object in JavaScript -- and perhaps this will lay the foundation for something that can be ported to Jackson (java?)
This is the convertData function that does the transform:
var convertData = function (d) {
var arr = [];
for(var prop in data)
{
var el = { "id": prop };
var otherprops = data[prop];
for(var otherprop in otherprops)
{
el[otherprop] = otherprops[otherprop];
}
arr.push(el);
}
return arr;
}
Tnis is what my sample data looks like after the conversion (slightly different values than yours):
[{"id":"-L8eoUd5mqJGnXDVSmb0","description":"With a great description","endDate":"12/31/2018","endTime":"03:00","imageUrl":"/favicon.ico","name":"Here's a Good Event","startDate":"12/01/2018","startTime":"12:00"},{"id":"-L8jO6Zhz976hvoLUiga","description":"Another item","endDate":"12/30/2018","endTime":"03:05","imageUrl":"/favicon2.ico","name":"Event #2","startDate":"12/11/2018","startTime":"12:03"}]
Link to JSFiddle: https://jsfiddle.net/2t1s2are/13/
Hope this helps!!

how insert " in numbers of my json [NODEJS]

i have a JSON like this:
{"name1":123,"name2":123,"name3":123}
i want put "" in numbers To stay like this:
{"name1":"123","name2":"123","name3":"123"}
Anybody know a nodejs code to do this?
Assuming the object is already parsed and stored in a variable somewhere, you can do:
Object.keys(myObject).reduce((o, k) => Object.assign(o, {
[k]: myObject[k].toString()
}), {})
As Judson Terrel was saying above, you should consider using JSON.stringify(myJsonObject)
but if you so desired to use regex, here it is
let str = '{"name1":123,"name2":123,"name3":123}';
let result = str.replace(/\b(\d+)/g, "\"$1\"");
console.log (result);
//console-output => {"name1":"123","name2":"123","name3":"123"}
The simplest way is to parse the JSON string to an object using JSON.parse, and then convert the object values to string with the String function, like this:
var strg = '{"name1":123,"name2":123,"name3":123}';
var obj = JSON.parse(strg);
for (var i in obj){
obj[i] = String(obj[i])
}
console.log(obj)

json C# 7 Tuple Support

I want to get my C#7 tuple property names in my JSON (Newtonsoft.Json) output.
My problem is:
When I want to convert my tuple to JSON format that not support my parameters names.
For example this is my "Test2" method and you can see the JSON output:
public void Test2()
{
var data = GetMe2("ok");
var jsondata = JsonConvert.SerializeObject(data);//JSON output is {"Item1":5,"Item2":"ok ali"}
}
public (int MyValue, string Name) GetMe2(string name)
{
return (5, name + " ali");
}
The JSON output is "{"Item1":5,"Item2":"ok ali"}" but i want "{"MyValue":5,"Name":"ok ali"}";
This is not impossible because I can get property names in runtime:
foreach (var item in this.GetType().GetMethods())
{
dynamic attribs = item.ReturnTypeCustomAttributes;
if (attribs.CustomAttributes != null && attribs.CustomAttributes.Count > 0)
{
foreach (var at in attribs.CustomAttributes)
{
if (at is System.Reflection.CustomAttributeData)
{
var ng = ((System.Reflection.CustomAttributeData)at).ConstructorArguments;
foreach (var ca in ng)
{
foreach (var val in (IEnumerable<System.Reflection.CustomAttributeTypedArgument>)ca.Value)
{
var PropertyNameName = val.Value;
Console.WriteLine(PropertyNameName);//here is property names of C#7 tuple
}
}
}
}
dynamic data = attribs.CustomAttributes[0];
var data2 = data.ConstructorArguments;
}
}
For the specific case here, it is impossible. That's because SerializeObject has no way of finding out where the tuple came from, all it sees is ValueTuple<int, string>.
The situation would be different if you were serializing an object with tuple properties, in which case SerializeObject could use reflection to find the TupleElementNames attributes (even though it currently doesn't).
The short answer it that tuples don't have properties.
A tuple is a bag of values used, mainly, to return multiple values from a method.
They were never intended to model entities.
The only way to solve your problem, if you don't want to create a type for that, is:
public void Test2()
{
var data = GetMe2("ok");
var jsondata = JsonConvert.SerializeObject(new { data.MyValue, data.Name });//JSON output is {"Item1":5,"Item2":"ok ali"}
}

Nodejs jsonArray parsing

I have a json object i want to get data from it!
here is my json object
"[androidVersionName=2.3.3, androidVersionId=10, androidId=fa0bef4b5a48eacb, mobileModel=sdk, mobileManufacturer=unknown, mobileId=GRI34, mobileProduct=sdk, applicationName=com.example.socketclient, applicationVersionName=1.0, applicationVersionCode=1, applicationState=INACTIVE, screenWidth=480, screenHeight=480, screenDensity=240, screenDensityName=hdpi, atdPackages=com.atd.panberes(1)]"
and here is my code :
var json = JSON.parse(data);
var androidVersionName = data.rowsets['androidVersionName'].row;
console.log(androidVersionName);
and i get this error :
Cannot read property 'androidVersionName' of undefined
how can i parse data from this jsonObject?
A valid JSON based on your object:
{
"androidVersionName":"2.3.3",
"androidVersionId":10,
"androidId":"fa0bef4b5a48eacb",
"mobileModel":"sdk",
"mobileManufacturer":"unknown",
"mobileId":"GRI34",
"mobileProduct":"sdk",
"applicationName":"com.example.socketclient",
"applicationVersionName":1.0,
"applicationVersionCode":1,
"applicationState":"INACTIVE",
"screenWidth":480,
"screenHeight":480,
"screenDensity":240,
"screenDensityName":"hdpi",
"atdPackages":"com.atd.panberes(1)"
}
You can't parse it to object. But you can transform it to JS object.
var data = "[androidVersionName=2.3.3, androidVersionId=10, androidId=fa0bef4b5a48eacb, mobileModel=sdk, mobileManufacturer=unknown, mobileId=GRI34, mobileProduct=sdk, applicationName=com.example.socketclient, applicationVersionName=1.0, applicationVersionCode=1, applicationState=INACTIVE, screenWidth=480, screenHeight=480, screenDensity=240, screenDensityName=hdpi, atdPackages=com.atd.panberes(1)]";
var result = {};
data.replace(/(\w+)=(\w+)/g, function(_, left, right) { result[left] = right; })
console.log(result);