I want to decode in extjs4 with Ext.decode(string), a json string with json string inside, just like this:
var string = "{success:true,
rows:[{"jsonfields":"[
{\\"name\\":\\"cm:title\\",\\"title\\":\\"Titolo\\",\\"description\\":\\"Titolo del contenuto\\",\\"dataType\\":\\"d:mltext\\",\\"url\\":\\"\/api\/property\/cm_title\\"},
{\\"name\\":\\"cm:content\\",\\"title\\":\\"Contenuto\\",\\"description\\":\\"Contenuto\\",\\"dataType\\":\\"d:content\\",\\"url\\":\\"\/api\/property\/cm_content\\"},
{\\"name\\":\\"cm:name\\",\\"title\\":\\"Nome\\",\\"description\\":\\"Nome\\",\\"dataType\\":\\"d:text\\",\\"url\\":\\"\/api\/property\/cm_name\\"}]"}
]}";
As you can see "jsonfields" is a json string code.
How I can decode this string with Ext.decode(string)
Any suggests?
There were a couple of problems with your JSON code.
All of your keys needed to be in quotes (success and rows were not).
Use single quotes when embedding a JSON string directly into javascript. This way you can avoid using the escape character.
Below is the correct JSON code. I have also updated your jsfiddle link.
var string = '{
"success": true,
"rows": [
{
"jsonfields": [
{
"name": "cm: title",
"title": "Titolo",
"description": "Titolodelcontenuto",
"dataType": "d: mltext",
"url": "/api/property/cm_title"
},
{
"name": "cm: content",
"title": "Contenuto",
"description": "Contenuto",
"dataType": "d: content",
"url": "/api/property/cm_content"
},
{
"name": "cm: name",
"title": "Nome",
"description": "Nome",
"dataType": "d: text",
"url": "/api/property/cm_name"
}
]
}
]}';
var decodedString = Ext.decode(string);
console.log(decodedString);
That's the correct way to decode JSON with Ext and the exception is likely telling you about some invalid syntax in your JSON string. The JSON format is very strict.
You can use an online validator like jsonlint to help figure out what's wrong with your syntax.
One other note: in cases like this, it's usually easier to use single quotes around your string so that you can embed double-quotes without having to escape them.
var string = '{ "success": true, ...}'
Related
I'm trying to send a custom JSON payload from my pipeline on Jenkins after the last successful stage, like this:
post {
success {
script {
def payload = """
{
"type": "AdaptiveCard",
"body": [
{
"type": "TextBlock",
"size": "Medium",
"weight": "Bolder",
"text": "SonarQube report from Jenkins Pipeline"
},
{
"type": "TextBlock",
"text": "Code was analyzed was successfully.",
"wrap": true,
"color": "Good",
"weight": "Bolder"
}
],
"$schema": "http://adaptivecards.io/schemas/adaptive-card.json",
"version": "1.3"
}"""
httpRequest httpMode: 'POST',
acceptType: 'APPLICATION_JSON',
contentType: 'APPLICATION_JSON',
url: "URL",
requestBody: payload
}
}
}
}
But I get an error
Error when executing success post condition:
groovy.lang.MissingPropertyException: No such property: schema for class: groovy.lang.Binding
at groovy.lang.Binding.getVariable(Binding.java:63)
I'm using the HTTP Request plugin available for Jenkins and the format of the JSON payload is correct for MS Teams.
The issue is actually a groovy syntax error. You can easily check this in something like https://groovy-playground.appspot.com/ by adding your def payload = ... statement.
There are multiple ways to get multiline strings in groovy:
triple single quoted string
triple double quoted string
slashy string
dollary slashy string
Apart from the single quoted string, they also have a secondary property which is interpolation
Notice how in the initial JSON payload, there's a "$schema" key? Using triple double quoted strings makes groovy want to find a schema variable and use it's value to construct that payload variable.
You have two separate solutions:
Use triple single quoted string - just update """ to '''
Escape the variable - just update "$schema" to "\$schema" (making $ a literal $ instead of it being used as an interpolation prefix)
I'm receiving a third-party API payload response like:
{
"message": "Validation failed because [{reason=CONDITIONAL_INVALID_VALUE, field=/targetingCriteria, batchIndex=0, type=INVALID_VALUE, message=/locale cannot be set to en if urn:li:adTargetingFacet:interfaceLocales is set to urn:li:locale:it_IT, parameters={field1=/locale, value2=urn:li:locale:it_IT, value1=en, field2=urn:li:adTargetingFacet:interfaceLocales, key=}}, {reason=FIELD_VALUE_TOO_LOW, field=dailyBudget, batchIndex=0, type=INVALID_VALUE, message=/dailyBudget/amount value 1 cannot be lower than 10.00, parameters={min=10.00, field=/dailyBudget/amount, costType=CPM, type=SPONSORED_UPDATES, value=1, key=}}]",
"status": 400
}
and I'd like to transform in something like:
{
"errors": [{
"reason": "CONDITIONAL_INVALID_VALUE",
"field": "/targetingCriteria",
"batchIndex": "0",
"type": "INVALID_VALUE",
"message": "/locale cannot be set to en if urn:li:adTargetingFacet:interfaceLocales is set to urn:li:locale:it_IT",
"parameters": "{field1=/locale, value2=urn:li:locale:it_IT, value1=en, field2=urn:li:adTargetingFacet:interfaceLocales, key=}"
},
{
"reason": "FIELD_VALUE_TOO_LOW",
"field": "dailyBudget",
"batchIndex": "0",
"type": "INVALID_VALUE",
"message": "/dailyBudget/amount value 1 cannot be lower than 10.00",
"parameters": "{min=10.00, field=/dailyBudget/amount, costType=CPM, type=SPONSORED_UPDATES, value=1, key=}"
}
]
}
But I'm struggling to find a clear golang approach to this problem, the main problems are:
no valid json is available: word are not correctly quoted with "
= symbol instead of :
nested graphs bracket
I'm currently try to transform in a valid json string and then parse as json but I have various problem with nested elements
Any idea?
EDIT: This is what I've done right now: https://play.golang.org/p/B7bdPCJoHc2
Currently been working on eliminating the excess "," comma on the json object I have below.
{"rules": {
"1000": {
"action": "2",
"category": "skype",
"entity": "Private",
"id": "1000",
},
"1200": {
"action": "2",
"category": "http",
"entity": "Public",
"id": "1200",
},
"100": {
"action": "2",
"category": "ftp",
"entity": "Public",
"id": "100",
},
"0": {
"entity": "Private",
"category": "alcohol, tobacco",
"action": "1",
"id": "low",
},
"3000": {
} }}
Maybe you have some insights on what's the cleanest way to eliminate it using AngularJS.
The data was parsed from this code snippet.
var request = {
url: 'sample/uri',
method: "GET",
transformResponse: specialTransform
};
var response = $q.defer( );
$http( request ).success( function( THIS DATA -> data, status ) {
eval
var fixTrailingCommas = function (jsonString) {
var jsonObj;
eval('jsonObj = ' + jsonString);
return JSON.stringify(jsonObj);
};
fixTrailingCommas('{"rules": { "1000": { "action": "2", "category": "skype", "entity": "Private", "id": "1000" , } } }');
Please use eval here only if you completely trust incoming json, and also be aware of other eval evils as described on MDN and its note on JSON parsing
Note that since JSON syntax is limited compared to JavaScript syntax, many valid JavaScript literals will not parse as JSON. For example, trailing commas are not allowed in JSON, and property names (keys) in object literals must be enclosed in quotes. Be sure to use a JSON serializer to generate strings that will be later parsed as JSON.
You may also choose to rely on implementation of JSON2 by Douglas Crockford which uses eval internally
On current browsers, this file does nothing,
preferring the built-in JSON object. There is no reason to use this file unless
fate compels you to support IE8, which is something that no one should ever
have to do again.
But because we really need to use this library, we have to make few code modifications, e.g. simply comment out JSON type check, which will then override native browser object (or we may also introduce new JSON2 global variable)
//if (typeof JSON !== 'object') {
JSON = {};
//}
P.S. Other parsing fuctions json_parse.js and json_parse_state.js, which don't use eval, throw a syntax error
Angular part
var config = {
transformResponse: function (data, headers) {
if(headers("content-type") === "application/json" && angular.isString(data)) {
try {
data = JSON.parse(data);
} catch (e) {
// if parsing error, try another parser
// or just fix commas, if you know for sure that the problem is in commas
data = JSON2.parse(data);
}
return data;
} else {
return data;
}
}
};
$http.get("rules.json", config).success(function (data) {
$scope.rules = data;
});
So as you said, the JSON is wrongly generated on the server you are taking it from, can you change the way it is generated there? (Follow this: Can you use a trailing comma in a JSON object?)
In case you are unable to do so, you need to use something like mentioned here:
Can json.loads ignore trailing commas?
library to repair a JSON object, like: https://www.npmjs.com/package/jsonrepair
(try some online fix tool here: http://www.javascriptformat.com/)
or some regexp magic
How i can escape characters for JSON with javascript in one page?
Here is js what i need used
bernhardhaeussner.de/odd/json-escape/ (here is text encoding after paste an click on ↓ escape ↓, but i need that text will be encode in load.)
github.com/douglascrockford/JSON-js/blob/ad6079cbd8dc362a3cc42e1f97c01aa5ccd48bfe/json2.js#L211
But i can't imagine how i can make it.
I need global code something like this.
<script>document.write(escape("Test code"));</script>
Give me example please man!:) Here is code what i have
{ "snippet": { "data": "2022-02-15T23:32:01.000Z", "data2": "2022-02-14T23:32:01.000Z", "data3": "t3", "data4": "test descr" }, "data": { "status": "bxx" }}
After escaped code is "{ \"snippet\": { \"data\": \"2022-02-15T23:32:01.000Z\", \"data2\": \"2022-02-14T23:32:01.000Z\", \"data3\": \"t3\", \"data4\": \"test descr\" }, \"data\": { \"status\": \"bxx\" }}"
How i can make it? Give please example with js. Thanks!
You don't have to do any "escaping" for JSON; just create the structure you want to turn into a JSON string, and use JSON.stringify to create the string. I'd give you an example but I can't begin to see from your question what you're trying to turn into JSON.
escape is completely unrelated to JSON (or just about anything else but unescape).
Re your update:
If you have a variable containing that structure, again, just use JSON.stringify on it:
var data = { "snippet": { "data": "2022-02-15T23:32:01.000Z", "data2": "2022-02-14T23:32:01.000Z", "data3": "t3", "data4": "test descr" }, "data": { "status": "bxx" }} ;
var json = JSON.stringify(data);
Should be a no brainer, but I'm can't seem to access the elements returned from Newtonsoft's json deserializer.
Example json:
{
"ns0:Test": {
"xmlns:ns0": "http:/someurl",
"RecordCount": "6",
"Record": [{
"aaa": "1",
"bbb": "2",
},
{
"aaa": "1",
"bbb": "2",
}]
}
}
var result = Newtonsoft.Json.JsonConvert.DeserializeObject<dynamic>(somestring);
Stripping out the json up to the Record text, i can access the data without issue.
i.e. result.Recordcount
If i leave the json as shown above, can someone enlighten me how to access Recordcount?
All inputs appreciated. Thanks!
For those JSON properties that have punctuation characters or spaces (such that they cannot be made into valid C# property names), you can use square bracket syntax to access them.
Try this:
int count = result["ns0:Test"].RecordCount;