how to parse string object without double quote in front in json - json

i have an array in my angular applicaton for eg:
searchTerm : any[]
I have a textbox with a value {'state':'tn'} and want to push this to the searchTerm array. Currently i add this item to a service and then array as:
private onItemAdded(event): void {
const filter = JSON.parse('"' + event['value'] + '"');
this.dataService.addFilter(filter);
}
But it is storing as "{'state':'tn'}"
How can i parse this without double quotes in the front?
console.log('ADDED FILTER', event['value']);
here the value is printed as {'state':'value'}
but when assign to variable as below, it adds double quotes
let filter = event['value'];
Thanks

why you are using parse?, it is for converting from JSON to object, instead use stringify which will parse your object to JSON(string)
const obj = "{'state':'tn'}";
let filter = JSON.stringify(obj);
filter = filter.slice(1, filter.length - 1);
console.log(filter);

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 []

How to get certain text from json object value

I am using react js. I have some json data where I am fetching the timestamp. It has date and time both. For example:
timestamp":"2020-03-23T14:00:00.000Z"
Now after fetching all the json data including timestamp. I wanna make a chart, but I only want to use the date in my chart, not the time. How do I only get the date from the timestamp in the form of 2020/03/23 not the- but with /? I am using chartjs for making the chart Thanks.
Edit:
for (const dataobj of json) {
let tempsymbolsDate = dataobj.timestamp.split("T")[0];
tempsymbolsDate.replace("-", "/"); //here it doesn't replace with `/`
console.log(tempsymbolsDate);
}
You can split the string using "2020-03-23T14:00:00.000Z".split("T")[0] to get the date without the time.
To replace - characters with /, use the str.replace(searchvalue, newvalue) method. For example:
"2020-03-23".replace(/-/g, "/")
Edit:
for (const dataobj of json) {
let tempsymbolsDate = dataobj.timestamp.split("T")[0];
tempsymbolsDate = tempsymbolsDate.replace(/-/g, "/");
console.log(tempsymbolsDate);
}
Edit 2:
for (const dataobj of json) {
let tempsymbolsDate = dataobj.timestamp.split("T")[0];
tempArray = tempsymbolsDate.split("-");
tempsymbolsDate = tempArray[2] + "/" + tempArray[1] + "/" + tempArray[0];
console.log(tempsymbolsDate);
}

Why am I getting Escaped Quotes? Json.net

I am not sure if I am doing this right. I got json stored in my database that I want to update.
var items = dbContext.items.FromSql("select *, JSON_VALUE(Attributes, '$.serialNumber') as serialNumber FROM Items WHERE JSON_VALUE(Attributes,'$.serialNumber') like '%15830792087%'").ToList();
var attributes = JObject.Parse(items[0].Attributes);
var images = attributes["image"];
if(images == null){
var newImage = new List<InventoryImage>()
{
new InventoryImage()
{
ImageUrl = imageBlob.Uri.AbsoluteUri,
OrignalName = file.FileName,
ThumbnailUrl = thumbnailBlob.Uri.AbsoluteUri
}
};
JProperty newProp = new JProperty("image", JsonConvert.SerializeObject(newImage));
attributes.Add(newProp);
images[0].Attributes = JsonConvert.SerializeObject(attributes);
dbContext.SaveChanges();
}
what I get in my db.
"image":"[{\"OrignalName\":\"cat-pet-animal-domestic-104827.jpeg\",\"ImageUrl\":\"ed1ab040e710.jpeg\",\"ThumbnailUrl\":\"3c3e73e3-5062-492b-b830-ed1ab040e710_thumbnail.jpeg\"}]"}
JProperty newProp = new JProperty("image", JsonConvert.SerializeObject(newImage));
This will serialize newImage into a JSON string and then assign that JSON string as the value to the image property. So the value of property is a string which happens to be a JSON string.
What you should do instead is assign the value directly without serializing it first. That way you avoid a double serialization:
Property newProp = new JProperty("image", JToken.FromObject(newImage));

Can't iterate through JSON object

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.

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)