RegEx to find json values without quotes - javascript

I'm having an issue with a parser (in this case PowerBI) not taking values that are not quoted.
The example JSON file which comes from an API is validating ok, but PowerBI is not having any of it:
{'requester_id': 361114274894, 'submitter_id': 361114274894, 'assignee_id': 361282665913, 'organization_id': 360009532534, 'group_id': 360000498954, 'name':'John Doe'}
I'd like to find all values without quotes so I can replace them.
Please help.

It seems like you'd like to convert your int values to string.
var json = {'requester_id': 361114274894, 'submitter_id': 361114274894, 'assignee_id': 361282665913, 'organization_id': 360009532534, 'group_id': 360000498954, 'name':'John Doe'}
Object.keys(json).forEach(i => json[i]=json[i].toString());
// output
json
{
assignee_id:"361282665913"
group_id:"360000498954"
name:"John Doe"
organization_id:"360009532534"
requester_id:"361114274894"
submitter_id:"361114274894"
}

The issue is with the use of single quotes instead of double quotes around the property names.
let correctedInput = input.replace(/'/g, '"');
let parsedInput = JSON.parse(correctedInput);
parsedInput will now be your javascript object.
input.replace(/'/g, '"') will find and replace all ' characters, and replace them with " characters. This should work fine unless any of your property values have single quotes in them - For example, the name O'malley will be parsed incorrectly.

You can use the for in loop. Assuming all non string items are numbers the following will work.
const obj = {
a: 123,
b: "234234",
c: 09,
};
console.log(obj);
for (key in obj) {
obj[key] = obj[key] + "";
}
console.log(obj);
If the goal is to gather all the keys with non-string values rather than replacing them you can save them to an array and manipulate them later:
const obj = {
a: 123,
b: "234234",
c: 09,
};
const arr = [];
for (key in obj) {
if (typeof obj[key] !== "string") {
arr.push(key);
}
}
console.log(arr);

You can perform the regex pattern matching as below in Java
String rtype="^\"|\"$";
String value = ((JSONObject) nameOfObject).get("key").toString().matches(rtype);
or
((JSONObject) nameOfObject).get("key").toString().replaceAll(rtype);

Related

How to convert string in an array?

From http response I received an object like this:
{"[3, company1]":["role_user"], "[4, company2]":["role_admin"] }
The key is an array...Is there a way in typescript to convert the key
"[3, company1]"
in an array like this
[3, "company1"]
?
You can combine Object.keys with map and transform the string to array with split
let data = {"[3, company1]":["role_user"], "[4, company2]":["role_admin"] }
let keys = Object.keys(data)
.map(
el =>
el.replace('[', '')
.replace(']', '')
.split(',')
.map(el => el.trim())
.map(el => isNaN(parseFloat(el))
? el
: parseFloat(el))
)
console.log("Keys: ", keys)
Here is the fiddle:
https://jsfiddle.net/to38g6cb/1/
What do you want to convert the keys to?
if want to convert it to a normal array then the below should do.
const httpResponse = {
"[3, company1]": ["role_user"],
"[4, company2]": ["role_admin"]
};
const convertedKeys = Object.keys(httpResponse).map(value => {
let keyArray = value.replace("[", "").replace("]", "").split(", ");
return [parseInt(keyArray[0]), keyArray[1]];
});
console.log(convertedKeys);
If the above is not what you wanted, please kindly rephrase your question again.
You can remove the first and last character using slice(1,-1) and split the string at /\s*,\s*/ (comma with optional spaces on either side).
Then convert the first part to a number and return the array
const input = {
"[3, company1]": ["role_user"],
"[4, company2]": ["role_admin"]
}
const output = Object.keys(input).map(k => {
const [n, comp] = k.slice(1,-1).split(/\s*,\s*/)
return [+n, comp]
})
console.log(JSON.stringify(output))
It would have been easier if the company1 part were already quoted, so that you could just use JSON.parse. In fact, let's just do that! Put quotes around the company1 part with search and replace.
let key = `[3, company1]`;
let obj = JSON.parse(key.replace(/[$A-Z_]\w*/gi, '"$&"'))
console.log(obj);
Note: I'm guessing at what characters might be valid and went with something that looks vaguely like a JavaScript identifier. [$A-Z_]\w* Obviously not commas and right square brackets, due to deserialization ambiguity.

javascript remove text with double inverted comma not working

I have a json object in a table like below
filter: {where: { AND:[{gender: {IN: "Female"}},{age: {LTE: 44}}]}, relativeDateRange: 90}
which I am fetching and need to change, By removing some of the text.
The new json object will look like below
{"filter": {"where": {"gender": {"IN": "Female"}, "age": {"LTE": 54}},"relativeDateRange": 90}}
One way of doing that is to stringify the object and replacing the keyword,
which in my "theory" should work. however by any mean I am not able to replace ('{"AND":') to blank.
The issue is the keyword contains double inverted comma.
below is the code:
s is the json object which contains the wrong json.
var stringified = JSON.stringify(s);
var t1 = stringified.replace("}{",", ").replace("}}]}","}}").replace('{"AND":', '')
var jsonObject = JSON.parse(t1);
console.log("new json:" +jsonObject);
The text which does not have double inverted comma is getting replaced.
Even using regex or escape character is not helping.
Any suggestion
One option you can try is to use the replacer function which is a parameter in JSON.stringify:
// Your initial filter object
const filter = {filter: {where: { AND:[{gender: {IN: "Female"}},{age: {LTE: 44}}]}, relativeDateRange: 90}};
// Define your replacer function:
const replacer = (name, value) => {
if (name === 'where') {
const array = value['AND'];
// Merge array elements or alter your output in any other way
return Object.assign({}, array[0], array[1]);
}
return value;
}
// The resulting output
console.log(JSON.stringify(filter, replacer, 2));
will produce the following output:
{
"filter": {
"where": {
"gender": {
"IN": "Female"
},
"age": {
"LTE": 44
}
},
"relativeDateRange": 90
}
}
I don't think it's the colon that's throwing off your text replacement statement. How about replacing the "AND" string first, before you complicate it by replacing the curley braces? It should not otherwise effect your other replacements.
var t1 = stringified.replace("AND:[","").replace("}{",", ").replace("}}]}","}}");
The final resolution or more precisely the problem i figure out was,
When a josn is stringified, Its add '\' before every word. As for example when below json is stringified.
filter: {where: { AND:[{gender: {IN: "Female"}},{age: {LTE: 44}}]}, relativeDateRange: 90}
it gives the output as
\filter: {\where: { \AND ....
And the simple resolution was to use replace with double backslash as below.
var t1 = stringified.replace('{\\"AND\\":','').replace(/}{/g,",").replace("}}},","}},").replace('{/"/":','')

Nested array formation with string in javascript

I have a string as "a.b.c.d:50" so i want to form an array with the above string as t[a][b][c][d]=50. so i have tried to split the code and form but this length of n values will generate dynamically. please let me know how we can achieve this.for fixed arrays i tried as below but not able to make this as for n number of arrays.
var str1="a.b.c.d:50";
var str=str1.split(":");
var dump=str[0].split(".");
t[dump[0]][dump[1]][dump[2]][dump[3]]=dump[4]
then result will be t[a][b][c][d]=50
You could take the JSON string, parse it and iterate all key/value pairs for a nested structure by saving the last key and crate new objects if not exist and assign the vlaue with the last property.
function setValue(object, path, value) {
var last = path.pop();
path.reduce((o, k) => o[k] = o[k] || {}, object)[last] = value;
}
var json = '{"subscriber.userTier.segment": "Red"}',
object = {};
Object
.entries(JSON.parse(json))
.forEach(([keys, value]) => setValue(object, keys.split('.'), value));
console.log(object);
Are you able to use ES6? This is something I just wrote quickly
var t = {a:{b:{c:{d:0}}}};
var str = "a.b.c.d:50"
var [chain, value] = str.split(':')
var parts = chain.split('.');
parts.slice(0, -1).reduce((c, v) => c[v], t)[parts[parts.length - 1]] = value;
console.log(t.a.b.c.d); // logs "50"
It works, however there is no error handling. If t['a']['b'] is undefined for example then you will get an uncaught TypeError, also if the string is in the incorrect format etc, it won't work.
At it's heart it uses reduce on the array ['a', 'b', 'c']. We pass t as the initial value for the reducer and then for each item in the array it does currentValue = currentValue[nextPart]. This will get you the object c, we then look at the last value in the parts array and set that property currentValue[lastPart] = value
That's a brief overview, hopefully you understand the rest of what's going on. If not feel free to ask :)
Quick and Dirty way of converting a string to a JSON object, if the string is constructed as a valid object.
var str = "a.b.c.d:50";
str = str.replace(/([a-z]){1}/gi, "\"$1\"");
str.split(".").forEach(function (value) {
str = str.replace(/\.(.*?)$/, ":{$1}");
});
var ar = JSON.parse("{"+str+"}");
console.log(ar);

save and display an array of JSON/JS object(name/value pair) value as a comma separated string

var obj = {
aray1:[1,2],
aray2:["a","b"],
aray3:["ab","abab"]
};
this is the object i have values and i want to store the above array values as as a comma separated string and display as comma separated string on UI.
DB used is Mongo.
I think you are looking for a join method on arrays.
What you can do is obj.aray1.join(",") which will return 1,2 that you can display in your UI
As #eddyP23 mentioned, [].join will do the job for you.
var obj = {
aray1:[1,2],
aray2:["a","b"],
aray3:["ab","abab"]
};
var result = "";
for(key in obj){
result += ","+obj[key].join(",")
}
console.log(result.substring(1));
var obj = {
aray1:[1,2],
aray2:["a","b"],
aray3:["ab","abab"]
};
var a = Object.keys(obj).map(function(key){
return obj[key]
})
console.log(a.toString())

Extract only values from JSON object in javascript without using a loop

is there a "Nice" way to get all the values out of a json object (I don't care about the keys) - just get the values into array,
without using a loop ?
(lang is Javascript)
It depends on how you define "loop".
You can extract the properties with Object.keys and then map them to their values.
… it's still essentially a loop under the hood though.
var json = `{ "foo": 1, "bar": 2, "baz": 3 }`;
var obj = JSON.parse(json);
var values = Object.keys(obj).map(function (key) { return obj[key]; });
console.log(values);
With weaker browser support you could use the values method.
var json = `{ "foo": 1, "bar": 2, "baz": 3 }`;
var obj = JSON.parse(json);
var values = Object.values(obj);
console.log(values);
I think you are looking for Object.values() function, just pass the object to the values method of Object as first param. That's it!
Object.values({something: 'lol'});
> ["lol"]
Recursively extract as text
Yes, this is a loop but the underlying methods you are calling such as Object.values or arr.map are still loops. I found this useful for extracting text out of a json object for full text search in particular and thought it useful as I came here initially needing this but the answers only touched the surface as json is recursive in nature.
function textFromJson(json) {
if (json === null || json === undefined) {
return '';
}
if (!Array.isArray(json) && !Object.getPrototypeOf(json).isPrototypeOf(Object)) {
return '' + json;
}
const obj = {};
for (const key of Object.keys(json)) {
obj[key] = textFromJson(json[key]);
}
return Object.values(obj).join(' ');
}
With ES2017 you have Object.values(). You can polyfill it also.
Only you need is transform JSON to JavaScript object and call Object.values(). The result is an array of values.
var obj = JSON.parse(jsonData);
var result = Object.values(obj);
If you pass a function to JSON.parse, it will be called each time a value is parsed:
function get_values(json) {
let values = []
JSON.parse(json, (key,value)=>{ values.push(value) })
return values
}
ex:
get_values(`{"a":1, "b":[true, false], "c":3}`)
// returns a list of:
• 1
• true
• false
• [true, false]
• 3
• {a:1, b:[true, false], c:3}
Note: If you don't consider the full object to be a "value", just remove the last item.

Categories

Resources