Json to Object Typescript - json

I have a Json object like so:
{
"key" : "false",
"key2" : "1.00",
"key3" : "value"
}
How can I convert this in Typescript to get
{
"key" : false,
"key2" : 1.00,
"key3" : "value"
}
I have tried using JSON.parse(JSON.stringify(json)), JSON.parse(json) and Object.assign(object, json) but none of those solutions seem to work.

The basic problem is that JSON.parse will not automatically convert strings that happen to represent valid values of primitives such as booleans and floats. It simply keeps them as strings. For a simple case, such as the one you have given, it's easy enough to manually convert the strings:
let src = { "key": "false", "key2": "1.00", "key3": "value" };
let dst = {
key: src.key !== "true",
key2: parseFloat(src.key2),
key3: src.key3
};

Related

How to convert a JSON object there in another object to string without any function

I want to post a json code to an API by Postman chrome app but as error that server gives to me one of values that is object, must be string e.g. lock at this json code:
{
"key1": "value",
"key2": {
"subkey1": {
"subsubkey1": "value",
"subsubkey2": "value"
},
"subkey2": "value",
},
"key3": "value"
}
As you see value of subkey1 is object, what I have to do in the code to its value be string?
I don't want use any function or anything else, I just want subkey1 value in this code be string!
I used this:
{
"key1": "value",
"key2": {
"subkey1": '{
"subsubkey1": "value",
"subsubkey2": "value"
}',
"subkey2": "value",
},
"key3": "value"
}
and this:
{
"key1": "value",
"key2": {
"subkey1": "{
"subsubkey1": "value",
"subsubkey2": "value"
}",
"subkey2": "value",
},
"key3": "value"
}
but API gave me invalid json error!
Your last attempt is close, but you need to escape the inner quote marks so that they don't terminate the outer string. A backslash (\) is normally used for this purpose:
"subkey1": "{
\"subsubkey1\": \"value\",
\"subsubkey2\": \"value\"
}"

Postgres, jsonb & jsonb_set

Depending on the HTTP_USER_AGENT I have to return a very specialized formatted version of a json structure to the client.
The json object is generated as usual with standard postgres functions.
Lets assume the generated json looks similar to this:
{
"return_code" : 0,
"payload" : {
"name" : "smith",
"age": 17,
"address" :{
"street" : "<whatever>",
"city" : "<anycity>"
}
}
}
Now under some circumstances I have to return this json in the following format:
{
"return_code" : 0,
"payload" : "{"name" : "smith", "age": 17, "address" :"{"street" : "<whatever>", "city" : "<anycity>"}"}"
}
As you can see the nested payload object should be returned as a string - masking ignored here for better readability.
Further else the address property should also be returned as a string, not as a json object.
My postgres code that should do this is simply:
response := jsonb_set(response, '{payload}', to_jsonb((response->'payload')::text));
But the result from the code above looks like:
{
"return_code" : 0,
"payload" : "{"name" : "smith", "age": 17, "address" :{"street" : "<whatever>", "city" : "<anycity>"}}"
}
Consider the quotes are missing (just two) for the address-object.
How can I fix this?
Thank You!
It seems to me that you need a further level of escaping / quoting on the address property, because you have:
Your substitution: { "payload" : { ... } } -> { "payload" : "{ ... }" }
Extra substitution: { "address": { ... } } -> { "address": "{ ... }" }
You'll need to do this before the existing line, so I think what you want is this (requires an extra jsonb variable, payload):
payload := jsonb_set(response->'payload', '{address}', to_jsonb((response->'payload'->address)::text));
response := jsonb_set(response, '{payload}', to_jsonb(payload::text));

Overwriting Documents in DocumentDB

I have a eventhub/stream analytics/documentdb chain, stream analytics job takes json object and persist it in a documentdb collection by id.
If a document with the same id exists in the collection, it should get overwritten right? But this is not happening.
let say I have this object in the collection:
{
"id" : "001",
"array":[
{
"key1" : "value1"
},
{
"key2" : "value2"
},
{
"key3" : "value3"
{
]
}
And the new document that is persisted by the stream job is :
{
"id" : "001",
"array":[
{
"key4" : "value4"
},
{
"key5" : "value5"
}
]
}
The new document that I get in the collection looks like this:
{
"id" : "001",
"array":[
{
"key4" : "value4"
},
{
"key5" : "value5"
},
{
"key3" : "value3"
{
]
}
The array doesn't get overwritten, only object within the size of the new document that is being saved. If oldarray.size > newarray.size some old data will still be there.
I want to prevent this. I want to overwrite all the document and get rid of all the old data.
Is there a way to do that?

Making valid json string with help of regex

I have an invalid json string that contains variables in a specific format.
A variable start with 'VV' then key (only alphanumeric, * and _ characters) then ends with 'VV'.
There are some places where these variables are defined in invalid json string, that can in inside value of any property or inside array.
I have to bring all variables inside the double quotes, if they are not already. So that the json string becomes a valid one.
One can assume that if all such variable is resolved, the json becomes a valid one.
My sandbox is https://regex101.com/r/uE9vB2/6
I have spent so much time but i could not found a way to get this issue resolved.
PS : I am not able to resolve the array entities.
Edit : Grouping is not required, as i am using separate grouping structure. I just want to replace those variable with "was-a-var" for both in objects and array.
for input :
{
"arr1": [
"key9",
VVvariable1VV,
"VVvariable2VV"
"key6",
"key7"
],
"obj1": {
"key1": "VVvaria*ble3VV",
"key3": VVvariable4VV,
"key7": "value7"
},
"obj2": {
"key1": {
"key1": "value-changed",
"key5": "VVvari_able5VV",
"key6": "value6",
"key7": VV*VV
},
"key2": [
"VVvariableVV",
VV*VV
]
},
"key8" : "value",
"key3": VVvariableVV,
"key5": "VVvariableVV"
}
Expected string :
{
"arr1": [
"key9",
"was-a-var",
"VVvariable2VV"
"key6",
"key7"
],
"obj1": {
"key1": "VVvaria*ble3VV",
"key3": "was-a-var",
"key7": "value7"
},
"obj2": {
"key1": {
"key1": "value-changed",
"key5": "VVvari_able5VV",
"key6": "value6",
"key7": "was-a-var"
},
"key2": [
"VVvariableVV",
"was-a-var"
]
},
"key8" : "value",
"key3": "was-a-var",
"key5": "VVvariableVV"
}
Edit : javascript regex only.
You can use the following to match:
(?<!")VV[\w*]*?VV(?!")
And replace with the following:
"was-a-var"
See RegEx DEMO
Edit: For javascript:
([^"])VV[\w*]*?VV(?!")
and replace with:
$1"was-a-var"
See DEMO

Parsing data and transferring it between views with SwiftyJSON and AlamoFire

I'm trying to deserialize a JSON object that is held in an Array. I'm using SwiftyJSON but the program is not behaving as I expected.
This is the array:
var GamesList = [JSON]();
The array holds my 2 JSON objects:
{
"game_type" : "TRADITIONAL",
"game_player_winner" : "",
"game_state" : "STARTED",
"self_left" : "2",
"self_right" : "1",
"self_name" : "test2",
"opponent_right" : "1",
"opponent_name" : "test1",
"game_guid" : "153fac87-bfc4-367f-41fa-944753dc32c8",
"game_idle_time" : 755858,
"opponent_left" : "3"
}, {
"game_type" : "TRADITIONAL",
"game_player_winner" : "",
"game_state" : "STARTED",
"self_left" : "2",
"self_right" : "1",
"self_name" : "test2",
"opponent_right" : "1",
"opponent_name" : "johannesswart",
"game_guid" : "153fac87-bfc4-367f-41fa-944753dc32c9",
"game_idle_time" : 755858,
"opponent_left" : "3"
}]hier is je gamestate: Optional({
"game_type" : "TRADITIONAL",
"game_player_winner" : "",
"game_state" : "STARTED",
"self_left" : "2",
"self_right" : "1",
"self_name" : "test2",
"opponent_right" : "1",
"opponent_name" : "testuser",
"game_guid" : "153fac87-bfc4-367f-41fa-944753dc32c9",
"game_idle_time" : 755858,
"opponent_left" : "3"
}
I create a new JSON object and fill it with a value of object 1 from the Array:
var gameState : JSON?;
self.gameState = GamesList[1];
When I print the entire self.gameState object to the console all is well and it looks like what I expected. However when I want to just use 1 value of this JSON object I can't seem to get it to work.
I tried with:
self.gameState["game_type"].string;
And:
var foo = JSON(self.gameState);
But this is both not compiling. What am I doing wrong?
I can see where this can be frustrating, but this is actually a pretty simple fix.
I had your same problem a while back when doing work with AlamoFire.
I can see why it's not compiling though, you are trying to retrieve a key out of an Array like:
self.gameState["game_type"]
but the Array type doesn't have key:value pairs, simple it is accessed via indexes:
self.gameState[1]
Step 1
So instead of an array, get your JSON into a dictionary. After that, follow these steps:
Make sure that your JSON data is being stored in a dictionary, like:
let jsonData: [String:String] = //your JSON
(use the var keyboard if you will be manipulating data in jsonData.
Step 2
After your JSON data is stored in a dictionary, simply do:
let gameState = jsonData["game_type"]!
You should not have a problem after that.
I hope I was able to shed some light, please comment if anything was unclear.