Swift: Incorrect Base64 Encoding - python

I am attempting to convert a block of code from python and it involved encoding a json string to base64. My attempt on Swift does not produce the same base64 encoded string.
Python:
payload_nonce = datetime.datetime(2022, 10, 10, 0, 0, 0).timestamp()
payload = {"request": "/v1/mytrades", "nonce": payload_nonce}
encoded_payload = json.dumps(payload).encode()
b64 = base64.b64encode(encoded_payload)
print(b64)
//prints b'eyJyZXF1ZXN0IjogIi92MS9teXRyYWRlcyIsICJub25jZSI6IDE2NjUzMzEyMDAuMH0='
Swift:
let formatter = DateFormatter()
formatter.dateFormat = "dd/MM/yyyy"
let date = formatter.date(from: "10/10/2022")
let payloadNonce = date!.timeIntervalSince1970
payload = [
"request": "/v1/mytrades",
"nonce": String(describing: payloadNonce)
]
do {
let json = try JSONSerialization.data(withJSONObject: payload)
let b64 = json.base64EncodedString()
print(b64)
//prints eyJyZXF1ZXN0IjoiXC92MVwvbXl0cmFkZXMiLCJub25jZSI6IjE2NjUzMzEyMDAuMCJ9
} catch {//handle error}
What am I missing?

Decoding the Python payload:
{"request": "/v1/mytrades", "nonce": 1665331200.0}
Decoding the Swift payload:
{"request":"\/v1\/mytrades","nonce":"1665331200.0"}
Firstly, it's clear the payloads are different.
You're using the String(describing:) initializer in Swift so nonce is being converted to a String rather than the raw floating-point value.
Secondly, JSONSerialization.data is escaping the forward slashes automatically when encoding. We can disable this optionally.
Now, other than the space between the keys in Python, the two outputs are the same.
Fixed example:
let formatter = DateFormatter()
formatter.dateFormat = "dd/MM/yyyy"
let date = formatter.date(from: "10/10/2022")
let payloadNonce = date!.timeIntervalSince1970
let payload: [String: Any] = [
"request": "/v1/mytrades",
"nonce": payloadNonce
]
do {
let json = try JSONSerialization.data(withJSONObject: payload, options: .withoutEscapingSlashes)
print(String(data: json, encoding: .utf8)!)
let b64 = json.base64EncodedString()
print(b64)
} catch {
}

When I decode the base64 strings, I get this for the Python code:
echo "eyJyZXF1ZXN0IjogIi92MS9teXRyYWRlcyIsICJub25jZSI6IDE2NjUzMzEyMDAuMH0=" | base64 -d
{"request": "/v1/mytrades", "nonce": 1665331200.0}
And this for the Swift code:
echo "eyJyZXF1ZXN0IjoiXC92MVwvbXl0cmFkZXMiLCJub25jZSI6IjE2NjUzMzEyMDAuMCJ9" | base64 -d
{"request":"\/v1\/mytrades","nonce":"1665331200.0"}
It appears that the slashes in the Swift code are escaped. To fix that, see this Stack Overflow answer: Swift String escaping when serializing to JSON using Codable.
The nonce is also a float in the Python response and a string in the Swift response.

Related

send payload in requests python

How to transfer payload as a string in requests python?
my code:
def send():
url = "url"
cookies = {
"csrf_token":"",
"refresh_token":"",
"access_token":""
}
data = "id%5B%5D=52626995&id%5B%5D=52627067&result_element%5BNAME%5D=%D0%90%D1%80%D0%BA%D0%B0%D0%B4%D0%B8%D0%B9&result_element%5BMAIN_USER_ID%5D=8272126&result_element%5BTAGS%5D%5B%5D=559091&result_element%5BTAGS%5D%5B%5D=559091&result_element%5Bcfv%5D%5B664393%5D%5B%5D=%7B%22DESCRIPTION%22%3A%22WORK%22%2C%22VALUE%22%3A%2271111111111%22%7D&result_element%5Bcfv%5D%5B664393%5D%5B%5D=%7B%22DESCRIPTION%22%3A%22WORK%22%2C%22VALUE%22%3A%2271111111111%22%7D&result_element%5Bcfv%5D%5B1262415%5D=12&result_element%5Bcfv%5D%5B1256527%5D=3&result_element%5Bcfv%5D%5B1272573%5D=817683&result_element%5BLEADS%5D%5B%5D=36375665&result_element%5BID%5D=52627067"
resp = requests.post(url=url, cookies=cookies, data=data)
return resp
But i got error cause data must be dict
They are right. It has to be a dictionary. The data you have here is also an encoded dictionary. Using (https://www.url-encode-decode.com/) you can understand your data better.
id[]=52626995
id[]=52627067
result_element[NAME]=Аркадий
result_element[MAIN_USER_ID]=8272126
result_element[TAGS][]=559091
result_element[TAGS][]=559091
result_element[cfv][664393][]={"DESCRIPTION":"WORK","VALUE":"71111111111"}
result_element[cfv][664393][]={"DESCRIPTION":"WORK","VALUE":"71111111111"}
result_element[cfv][1262415]=12
result_element[cfv][1256527]=3
result_element[cfv][1272573]=817683
result_element[LEADS][]=36375665
result_element[ID]=52627067
As a normal python dictionary, this is the following
{
"id": [52626995, 52627067],
"result_element": {
"NAME": "Аркадий",
"MAIN_USER_ID": 8272126,
"TAGS": [559091, 559091],
"cfv": {
664393: [
{"DESCRIPTION":"WORK","VALUE":"71111111111"},
{"DESCRIPTION":"WORK","VALUE":"71111111111"}],
1262415: 12,
1256527: 3,
1272573: 817683,
},
"LEADS": [36375665],
"ID": 52627067
}
}
So if you have the following code, it should work:
url = "url"
cookies = {
"csrf_token":"",
"refresh_token":"",
"access_token":""
}
data = {"id": [52626995, 52627067],
"result_element": {
"NAME": "Аркадий",
"MAIN_USER_ID": 8272126,
"TAGS": [559091, 559091],
"cfv": {
664393: [
{"DESCRIPTION":"WORK","VALUE":"71111111111"},
{"DESCRIPTION":"WORK","VALUE":"71111111111"}],
1262415: 12,
1256527: 3,
1272573: 817683,
},
"LEADS": [36375665],
"ID": 52627067
}
}
resp = requests.post(url=url, cookies=cookies, data=data)
return resp
I did it manually. First, check whether I have correctly parsed your string.
Check out the requests documentation
data – (optional) Dictionary, list of tuples, bytes, or file-like object to send in the body of the Request.
So only thing you need is to encode your string to bytes:
resp = requests.post(url=url, cookies=cookies, data=data.encode())
The more detailed explanation is that strings in Python 3 are abstract representation of the characters you see. You can use Czech letter "Ř" in Python regardless what encoding is used to represent the characters as bytes in the computer memory.
However, to send it over internet, you have to send it encoded as bytes.
If you would like to get those bytes, you have to specify the encoding that converts characters to bytes representing them. For Czech, the most appropriate is UTF-8 (as for almost anything) or maybe Windows-1250 aka CP-1250:
>>> x = "Ř"
>>> x
'Ř'
>>> x.encode("utf-8")
b'\xc5\x98'
>>> x.encode("cp1250")
b'\xd8'
Plain str.encode without encoding specified uses UTF-8, probably the best choice:
>>> x.encode()
b'\xc5\x98'

Transforming queries in a URL

I'm trying to use a REST API apparently constructed with LoopBack and it requires that my filter parameters be encoded in a specific way.
What is this sort of transformation called?
# this is a JSON type encoding
...?filter={"where": {"StartDate": {"gte": "2021-01-01T00:00:00.000Z"}}, "offset": 0, "limit": 100, "order": "id DESC" }
which needs to be encoded as some sort of HTTP query string
...?filter=%7B%22where%22%3A%20%7B%22StartDate%22%3A%20%7B%22gte%22%3A%20%222021-06-01T00%3A00%3A00.000Z%22%7D%7D%2C%20%22offset%22%3A%200%2C%20%22limit%22%3A%20100%2C%20%22order%22%3A%20%22id%20DESC%22%20%7D
Is there a python function to do this?
This is URL encoding.
URLs cannot contain a lot of different special characters, such as spaces (a space would be %20 in URL encoding).
Note that URL encoding is quite easy to recognize once you know it exists, due to the %xx pattern.
The urllib has functions to deal with encoding/decoding this.
To create an URL encoded string use urllib.parse.quote(string). Relevant docs here...
Example
from urllib.parse import quote
jsonstring = '{"where": {"StartDate": {"gte": "2021-01-01T00:00:00.000Z"}}, "offset": 0, "limit": 100, "order": "id DESC" }'
urlencoded = quote(jsonstring)
print(urlencoded)
# output
# %7B%22where%22%3A%20%7B%22StartDate%22%3A%20%7B%22gte%22%3A%20%222021-01-01T00%3A00%3A00.000Z%22%7D%7D%2C%20%22offset%22%3A%200%2C%20%22limit%22%3A%20100%2C%20%22order%22%3A%20%22id%20DESC%22%20%7D
You are looking for URL encoding. If you already have the JSON encoded in a variable as such, then just encode it to the filter parameter:
from urllib.parse import urlencode, quote
base_url = "..."
filter_string = """{"where": {"StartDate": {"gte": "2021-01-01T00:00:00.000Z"}}, "offset": 0, "limit": 100, "order": "id DESC" }"""
query = urlencode({"filter": filter_string}, quote_via=quote)
url = f"{base_url}?{query}"
Now, I expect that the JSON is probably coming from a Python data structure. You can use the dumps function from json to handle that encoding:
from urllib.parse import urlencode, quote
import json
base_url = "..."
data = {
"where": {
"StartDate": {
"gte": "2021-01-01T00:00:00.000Z"
}
},
"offset": 0,
"limit": 100,
"order": "id DESC"
}
filter_string = json.dumps(data)
query = urlencode({"filter": filter_string}, quote_via=quote)
url = f"{base_url}?{query}"
And you have the URL to call to in the variable url.

Python requests, how to send json request without " "

my code looks like
data = {
"undelete_user":'false'
}
data_json = json.dumps(data)
print(data_json)
Output is:
{"undelete_user": "false"}
i need output to be without "" so it can look like
{"undelete_user": false}
otherwise when i send request, i will get "failed to decode JSON" error
import json
data = {
"undelete_user": False
}
data_json = json.dumps(data)
print(data_json)
All you had to do was remove 'false' and put False, because you're considering your false as a string, and it should be a boolean.
I hope it helped!

Convert Python dictionary to a JSON array

Here's my function which connects to an API:
def order_summary():
"""Get order summary for a specific order"""
# Oauth2 params
headerKey = api_login()
headers = {'Authorization': headerKey}
# Payload params
payloadOrderSum = {
"domainId": 15,
"domainName": "SGL",
"orderId": 3018361
}
# API response
orderSumResp = requests.post(url + "order/summary", data=payloadOrderSum, headers=headers)
print(orderSumResp.content)
The API expects a JSON array as Payload Params which essentially looks like that:
[
{
"domainId": 0,
"domainName": "string",
"orderId": 0
}
]
The other endpoints I coded for on this API didn't need for the params to be an array so I could just use them as is and send them as a dictionary and it worked.
I've tried a couple things using the JSON library but I can't seem to get it to work. I saw that the JSonEncoder converts lists and tuples to JSON arrays but I couldn't figure it out.
Not sure what other info I could provide but just ask if there are any.
Thanks!
Wrap payloadOrderSum into a list:
payloadOrderSum = {
"domainId": 15,
"domainName": "SGL",
"orderId": 3018361
}
orderSumResp = requests.post(url + "order/summary", json=[payloadOrderSum], headers=headers)
Note that I used json kwarg instead of data (added in version 2.4.2).
dump your dict with json.dumps requests-doc
r = requests.post(url, data=json.dumps(payload))
It could help if you specify what you tried with the JSON library.
However, you might wanna try this if you haven't already done so:
import json
payloadOrderSum = json.dumps(
{
"domainId": 15,
"domainName": "SGL",
"orderId": 3018361
}
)

Unwanted double quotes around server response in Python Flask-RESTful [duplicate]

Given a string of JSON data, how can I safely turn that string into a JavaScript object?
Obviously I can do this unsafely with something like:
var obj = eval("(" + json + ')');
but that leaves me vulnerable to the JSON string containing other code, which it seems very dangerous to simply eval.
JSON.parse(jsonString) is a pure JavaScript approach so long as you can guarantee a reasonably modern browser.
The jQuery method is now deprecated. Use this method instead:
let jsonObject = JSON.parse(jsonString);
Original answer using deprecated jQuery functionality:
If you're using jQuery just use:
jQuery.parseJSON( jsonString );
It's exactly what you're looking for (see the jQuery documentation).
This answer is for IE < 7, for modern browsers check Jonathan's answer above.
This answer is outdated and Jonathan's answer above (JSON.parse(jsonString)) is now the best answer.
JSON.org has JSON parsers for many languages including four different ones for JavaScript. I believe most people would consider json2.js their goto implementation.
Use the simple code example in "JSON.parse()":
var jsontext = '{"firstname":"Jesper","surname":"Aaberg","phone":["555-0100","555-0120"]}';
var contact = JSON.parse(jsontext);
and reversing it:
var str = JSON.stringify(arr);
This seems to be the issue:
An input that is received via Ajax websocket etc, and it will be in String format, but you need to know if it is JSON.parsable. The touble is, if you always run it through JSON.parse, the program MAY continue "successfully" but you'll still see an error thrown in the console with the dreaded "Error: unexpected token 'x'".
var data;
try {
data = JSON.parse(jqxhr.responseText);
} catch (_error) {}
data || (data = {
message: 'Server error, please retry'
});
I'm not sure about other ways to do it but here's how you do it in Prototype (JSON tutorial).
new Ajax.Request('/some_url', {
method:'get',
requestHeaders: {Accept: 'application/json'},
onSuccess: function(transport){
var json = transport.responseText.evalJSON(true);
}
});
Calling evalJSON() with true as the argument sanitizes the incoming string.
If you're using jQuery, you can also use:
$.getJSON(url, function(data) { });
Then you can do things like
data.key1.something
data.key1.something_else
etc.
Just for fun, here is a way using a function:
jsonObject = (new Function('return ' + jsonFormatData))()
$.ajax({
url: url,
dataType: 'json',
data: data,
success: callback
});
The callback is passed the returned data, which will be a JavaScript object or array as defined by the JSON structure and parsed using the $.parseJSON() method.
Using JSON.parse is probably the best way.
Here's an example
var jsonRes = '{ "students" : [' +
'{ "firstName":"Michel" , "lastName":"John" ,"age":18},' +
'{ "firstName":"Richard" , "lastName":"Joe","age":20 },' +
'{ "firstName":"James" , "lastName":"Henry","age":15 } ]}';
var studentObject = JSON.parse(jsonRes);
The easiest way using parse() method:
var response = '{"result":true,"count":1}';
var JsonObject= JSON.parse(response);
Then you can get the values of the JSON elements, for example:
var myResponseResult = JsonObject.result;
var myResponseCount = JsonObject.count;
Using jQuery as described in the jQuery.parseJSON() documentation:
JSON.parse(jsonString);
Try using the method with this Data object. ex:Data='{result:true,count:1}'
try {
eval('var obj=' + Data);
console.log(obj.count);
}
catch(e) {
console.log(e.message);
}
This method really helps in Nodejs when you are working with serial port programming
I found a "better" way:
In CoffeeScript:
try data = JSON.parse(jqxhr.responseText)
data ||= { message: 'Server error, please retry' }
In Javascript:
var data;
try {
data = JSON.parse(jqxhr.responseText);
} catch (_error) {}
data || (data = {
message: 'Server error, please retry'
});
JSON parsing is always a pain. If the input is not as expected it throws an error and crashes what you are doing.
You can use the following tiny function to safely parse your input. It always turns an object even if the input is not valid or is already an object which is better for most cases:
JSON.safeParse = function (input, def) {
// Convert null to empty object
if (!input) {
return def || {};
} else if (Object.prototype.toString.call(input) === '[object Object]') {
return input;
}
try {
return JSON.parse(input);
} catch (e) {
return def || {};
}
};
Parse the JSON string with JSON.parse(), and the data becomes a JavaScript object:
JSON.parse(jsonString)
Here, JSON represents to process JSON dataset.
Imagine we received this text from a web server:
'{ "name":"John", "age":30, "city":"New York"}'
To parse into a JSON object:
var obj = JSON.parse('{ "name":"John", "age":30, "city":"New York"}');
Here obj is the respective JSON object which looks like:
{ "name":"John", "age":30, "city":"New York"}
To fetch a value use the . operator:
obj.name // John
obj.age //30
Convert a JavaScript object into a string with JSON.stringify().
JSON.parse(jsonString);
json.parse will change into object.
JSON.parse() converts any JSON string passed into the function into a JSON object.
To understand it better, press F12 to open "Inspect Element" in your browser and go to the console to write the following commands:
var response = '{"result":true,"count":1}'; //sample json object(string form)
JSON.parse(response); //converts passed string to JSON Object.
Now run the command:
console.log(JSON.parse(response));
You'll get output as an Object {result: true, count: 1}.
In order to use that Object, you can assign it to the variable, maybe obj:
var obj = JSON.parse(response);
By using obj and the dot (.) operator you can access properties of the JSON object.
Try to run the command:
console.log(obj.result);
Official documentation:
The JSON.parse() method parses a JSON string, constructing the JavaScript value or object described by the string. An optional reviver function can be provided to perform a transformation on the resulting object before it is returned.
Syntax:
JSON.parse(text[, reviver])
Parameters:
text
: The string to parse as JSON. See the JSON object for a description of JSON syntax.
reviver (optional)
: If a function, this prescribes how the value originally produced by parsing is transformed, before being returned.
Return value
The Object corresponding to the given JSON text.
Exceptions
Throws a SyntaxError exception if the string to parse is not valid JSON.
If we have a string like this:
"{\"status\":1,\"token\":\"65b4352b2dfc4957a09add0ce5714059\"}"
then we can simply use JSON.parse twice to convert this string to a JSON object:
var sampleString = "{\"status\":1,\"token\":\"65b4352b2dfc4957a09add0ce5714059\"}"
var jsonString= JSON.parse(sampleString)
var jsonObject= JSON.parse(jsonString)
And we can extract values from the JSON object using:
// instead of last JSON.parse:
var { status, token } = JSON.parse(jsonString);
The result will be:
status = 1 and token = 65b4352b2dfc4957a09add0ce5714059
Performance
There are already good answer for this question, but I was curious about performance and today 2020.09.21 I conduct tests on MacOs HighSierra 10.13.6 on Chrome v85, Safari v13.1.2 and Firefox v80 for chosen solutions.
Results
eval/Function (A,B,C) approach is fast on Chrome (but for big-deep object N=1000 they crash: "maximum stack call exceed)
eval (A) is fast/medium fast on all browsers
JSON.parse (D,E) are fastest on Safari and Firefox
Details
I perform 4 tests cases:
for small shallow object HERE
for small deep object HERE
for big shallow object HERE
for big deep object HERE
Object used in above tests came from HERE
let obj_ShallowSmall = {
field0: false,
field1: true,
field2: 1,
field3: 0,
field4: null,
field5: [],
field6: {},
field7: "text7",
field8: "text8",
}
let obj_DeepSmall = {
level0: {
level1: {
level2: {
level3: {
level4: {
level5: {
level6: {
level7: {
level8: {
level9: [[[[[[[[[['abc']]]]]]]]]],
}}}}}}}}},
};
let obj_ShallowBig = Array(1000).fill(0).reduce((a,c,i) => (a['field'+i]=getField(i),a) ,{});
let obj_DeepBig = genDeepObject(1000);
// ------------------
// Show objects
// ------------------
console.log('obj_ShallowSmall:',JSON.stringify(obj_ShallowSmall));
console.log('obj_DeepSmall:',JSON.stringify(obj_DeepSmall));
console.log('obj_ShallowBig:',JSON.stringify(obj_ShallowBig));
console.log('obj_DeepBig:',JSON.stringify(obj_DeepBig));
// ------------------
// HELPERS
// ------------------
function getField(k) {
let i=k%10;
if(i==0) return false;
if(i==1) return true;
if(i==2) return k;
if(i==3) return 0;
if(i==4) return null;
if(i==5) return [];
if(i==6) return {};
if(i>=7) return "text"+k;
}
function genDeepObject(N) {
// generate: {level0:{level1:{...levelN: {end:[[[...N-times...['abc']...]]] }}}...}}}
let obj={};
let o=obj;
let arr = [];
let a=arr;
for(let i=0; i<N; i++) {
o['level'+i]={};
o=o['level'+i];
let aa=[];
a.push(aa);
a=aa;
}
a[0]='abc';
o['end']=arr;
return obj;
}
Below snippet presents chosen solutions
// src: https://stackoverflow.com/q/45015/860099
function A(json) {
return eval("(" + json + ')');
}
// https://stackoverflow.com/a/26377600/860099
function B(json) {
return (new Function('return ('+json+')'))()
}
// improved https://stackoverflow.com/a/26377600/860099
function C(json) {
return Function('return ('+json+')')()
}
// src: https://stackoverflow.com/a/5686237/860099
function D(json) {
return JSON.parse(json);
}
// src: https://stackoverflow.com/a/233630/860099
function E(json) {
return $.parseJSON(json)
}
// --------------------
// TEST
// --------------------
let json = '{"a":"abc","b":"123","d":[1,2,3],"e":{"a":1,"b":2,"c":3}}';
[A,B,C,D,E].map(f=> {
console.log(
f.name + ' ' + JSON.stringify(f(json))
)})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
This shippet only presents functions used in performance tests - it not perform tests itself!
And here are example results for chrome
Converting the object to JSON, and then parsing it, works for me, like:
JSON.parse(JSON.stringify(object))
The recommended approach to parse JSON in JavaScript is to use JSON.parse()
Background
The JSON API was introduced with ECMAScript 5 and has since been implemented in >99% of browsers by market share.
jQuery once had a $.parseJSON() function, but it was deprecated with jQuery 3.0. In any case, for a long time, it was nothing more than a wrapper around JSON.parse().
Example
const json = '{ "city": "Boston", "population": 500000 }';
const object = JSON.parse(json);
console.log(object.city, object.population);
Browser Compatibility
Is JSON.parse supported by all major browsers?
Pretty much, yes (see reference).
Older question, I know, however nobody notice this solution by using new Function(), an anonymous function that returns the data.
Just an example:
var oData = 'test1:"This is my object",test2:"This is my object"';
if( typeof oData !== 'object' )
try {
oData = (new Function('return {'+oData+'};'))();
}
catch(e) { oData=false; }
if( typeof oData !== 'object' )
{ alert( 'Error in code' ); }
else {
alert( oData.test1 );
alert( oData.test2 );
}
This is a little more safe because it executes inside a function and do not compile in your code directly. So if there is a function declaration inside it, it will not be bound to the default window object.
I use this to 'compile' configuration settings of DOM elements (for example the data attribute) simple and fast.
Summary:
Javascript (both browser and NodeJS) have a built in JSON object. On this Object are 2 convenient methods for dealing with JSON. They are the following:
JSON.parse() Takes JSON as argument, returns JS object
JSON.stringify() Takes JS object as argument returns JSON object
Other applications:
Besides for very conveniently dealing with JSON they have can be used for other means. The combination of both JSON methods allows us to make very easy make deep clones of arrays or objects. For example:
let arr1 = [1, 2, [3 ,4]];
let newArr = arr1.slice();
arr1[2][0] = 'changed';
console.log(newArr); // not a deep clone
let arr2 = [1, 2, [3 ,4]];
let newArrDeepclone = JSON.parse(JSON.stringify(arr2));
arr2[2][0] = 'changed';
console.log(newArrDeepclone); // A deep clone, values unchanged
You also can use reviver function to filter.
var data = JSON.parse(jsonString, function reviver(key, value) {
//your code here to filter
});
For more information read JSON.parse.
Just to the cover parse for different input types
Parse the data with JSON.parse(), and the data becomes a JavaScript object.
var obj = JSON.parse('{ "name":"John", "age":30, "city":"New York"}');
When using the JSON.parse() on a JSON derived from an array, the method will return a JavaScript array, instead of a JavaScript object.
var myArr = JSON.parse(this.responseText);
console.log(myArr[0]);
Date objects are not allowed in JSON.
For Dates do somthing like this
var text = '{ "name":"John", "birth":"1986-12-14", "city":"New York"}';
var obj = JSON.parse(text);
obj.birth = new Date(obj.birth);
Functions are not allowed in JSON.
If you need to include a function, write it as a string.
var text = '{ "name":"John", "age":"function () {return 30;}", "city":"New York"}';
var obj = JSON.parse(text);
obj.age = eval("(" + obj.age + ")");
Another option
const json = '{ "fruit": "pineapple", "fingers": 10 }'
let j0s,j1s,j2s,j3s
console.log(`{ "${j0s="fruit"}": "${j1s="pineapple"}", "${j2s="fingers"}": ${j3s="10"} }`)
Try this. This one is written in typescript.
export function safeJsonParse(str: string) {
try {
return JSON.parse(str);
} catch (e) {
return str;
}
}

Categories

Resources