This is the javascript Object (just a small part of it):
dataToReturn = {
"dimensionsDisplayType" : [
"dropdown","swatch",
],
"pwEnabledDimensionMap" : {
"size_name": true,
"color_name": true
},
"isPWBadgeEnabled" : true,
"isImmersiveExperience" : false,
"isTabletWeb" : false
}
So in PHP it will look like:
<?php
$jsObjStr = '{
"dimensionsDisplayType" : [
"dropdown","swatch",
],
"pwEnabledDimensionMap" : {
"size_name": true,
"color_name": true
},
"isPWBadgeEnabled" : true,
"isImmersiveExperience" : false,
"isTabletWeb" : false
}';
But if we would like to parse it with json parse we cant In PHP since its not a clean JSON format because of
"dimensionsDisplayType" : [
"dropdown","swatch",
]
The keys containing object like "dimensionsDisplayType" can be unpredictable so cleaning with regex for example wont help much.
The one that works is
JSON.stringify(dataToReturn)
But in my case I can not run client side code sot it must be converted into the correct JSON format in server side with PHP. I was searching a lot online but I got not any satisfying function or library.
How can this be solved ?
You could try cleaning the string with this regex, this will look for a comma followed by optional whitespace and a close ] and replace this with the content minus the comma...
$jsObjStr = preg_replace("/,(\s*?])/", "$1", $jsObjStr);
Related
I have an environment variable that I use within a body of a PATCH, I want to ensure that this matches the one within the response body of the same PATCH.
The environment variable and response body are structured exactly the same:
"compliance":{
"documents": true,
"shareInfo": true,
"applicationUnderstood": true,
"authoriseCheck": true,
"drivingLicenceType": "EU"
}
I've tried the following but it errored with 'TypeError: Cannot read property 'documents' of undefined'
pm.test("Assert ComplianceDetails", function () {
var complianceData = (pm.environment.get("Compliance"))
pm.expect(jsonData.compliance.documents).to.eql(complianceData.compliance.documents)
pm.expect(jsonData.compliance.shareInfo).to.eql(complianceData.compliance.shareInfo)
pm.expect(jsonData.compliance.applicationUnderstood).to.eql(complianceData.compliance.applicationUnderstood)
pm.expect(jsonData.compliance.authoriseCheck).to.eql(complianceData.compliance.authoriseCheck)
pm.expect(jsonData.compliance.drivingLicenceType).to.eql(complianceData.compliance.drivingLicenceType)
});
I've managed to get this to work using .split(' ') but don't want to make my tests brittle if something is to change in the future. Is there a way of using something like the above to get this to work? I don't really want to separate out the environment variable any further either.
if you have set postman varaible through script as :
pm.environment.set("Compliance",{"compliance":{
"documents": true,
"shareInfo": true,
"applicationUnderstood": true,
"authoriseCheck": true,
"drivingLicenceType": "EU"
}})
Then it will be stored as javascript object and your code works as it is:
var complianceData = (pm.environment.get("Compliance"))
pm.expect(jsonData.compliance.documents).to.eql(complianceData.compliance.documents)
pm.expect(jsonData.compliance.shareInfo).to.eql(complianceData.compliance.shareInfo)
pm.expect(jsonData.compliance.applicationUnderstood).to.eql(complianceData.compliance.applicationUnderstood)
pm.expect(jsonData.compliance.authoriseCheck).to.eql(complianceData.compliance.authoriseCheck)
pm.expect(jsonData.compliance.drivingLicenceType).to.eql(complianceData.compliance.drivingLicenceType)
Else if you have copy and pasted the content to environment variable, then it is stored as string , you have to parse it first:
var complianceData = JSON.parse(pm.environment.get("Compliance"))
pm.expect(jsonData.compliance.documents).to.eql(complianceData.compliance.documents)
pm.expect(jsonData.compliance.shareInfo).to.eql(complianceData.compliance.shareInfo)
pm.expect(jsonData.compliance.applicationUnderstood).to.eql(complianceData.compliance.applicationUnderstood)
pm.expect(jsonData.compliance.authoriseCheck).to.eql(complianceData.compliance.authoriseCheck)
pm.expect(jsonData.compliance.drivingLicenceType).to.eql(complianceData.compliance.drivingLicenceType)
Comment
below object is not a valid javascript object , you have to enclose it with curly bracket:
Invalid:
"compliance":{
"documents": true,
"shareInfo": true,
"applicationUnderstood": true,
"authoriseCheck": true,
"drivingLicenceType": "EU"
}
valid:
{
"compliance":{
"documents": true,
"shareInfo": true,
"applicationUnderstood": true,
"authoriseCheck": true,
"drivingLicenceType": "EU"
}
}
if you don't want to make to store it in that format, then in script you can do:
var complianceData = "{"+(pm.environment.get("Compliance"))+"}"
// or `{${pm.environment.get("Compliance")}}`
I need to pull the value of property "title"
KV = {
clientPath: '/0000000000/client',
serverPath: '',
application: '/00000000/client/application/player.js',
properties: '/000000000/client/custom-config/AppProperties.js',
pollingEnabled: false,
customerConfig: {},
presentationTypeConfig: {},
kuluConfig: {},
kulu: {
"guid" : "XXXXXXX",
"title" : "XXXXX",
"createdInApp" : false,
"allowFeedback" : true,
"publisher" : {
"id" : 000000001,
"username" : "XXXXXXX",
"name" : "XXXXXXXX"
},
I tried looping but I just get returned undefined.
I have no access to the code to change it.
Have you tried this?
KV.kulu.title
first of all: the json you have posted is invalid. publisher-property has only an opening curly bracket.
second: here's a working fiddle, with valid json and just the code kv.kulu.title which does exactly what you are (literally) asking for:
http://jsfiddle.net/k75cxdkh/1/
edit: I'm just guessing here, but re-reading your question and json code, it seems you try to loop over an array of objects to get a nested object by it's value dynamically. When trying this, do it e.g. like this (using underscorejs):
var arr = _.filter(KV, function(obj) {
return _.some(obj.kulu, {id: ID_TO_FIND});
});
if not, nevermind. It's just a bit weird you are asking for a such common task.
quick and easy: KV.kulu.title no loop required!
I'm working on a project, I can manually add a beginning name and parenthesis: bio(
and an ending ) to the end of my JSON data to make it callable as JSONP.
I am going to do this to about 200 files which is why I'm trying to find a solution to do this in code.
I've tried using regex, converting to a string, trying to convert back, etc, and nothing seems to work.
My abbreviated JSON data is below:
{
"Directory": {
"workbooks": ["/xl/workbook.xml"],
"sheets": ["/xl/worksheets/sheet1.xml"],
"style": "/xl/styles.xml",
"defaults": {
"xml": "application/xml",
"rels": "application/vnd.openxmlformats-package.relationships+xml"
}
},
"Workbook": {
"AppVersion": [null],
"Sheets": [
[null]
],
"CalcPr": [null],
"xmlns": "http://schemas.openxmlformats.org/spreadsheetml/2006/main"
}
What I want is:
bio({ <--------
"Directory": {
"workbooks": ["/xl/workbook.xml"],
"sheets": ["/xl/worksheets/sheet1.xml"],
"style": "/xl/styles.xml",
"defaults": {
"xml": "application/xml",
"rels": "application/vnd.openxmlformats-package.relationships+xml"
}
},
"Workbook": {
"AppVersion": [null],
"Sheets": [
[null]
],
"CalcPr": [null],
"xmlns": "http://schemas.openxmlformats.org/spreadsheetml/2006/main"
}) <-------
I've gotten closest with Stringify and regex:
var myString = JSON.stringify(workbook);
var change = myString.replace(/^/,"bioInfo(").replace(/$/,")”);
When I try to change it back to an object so I can use it though, it fails saying:
JSON.parse: unexpected character at line 1 column 1 of the JSON data
I've tried eval as well trying to get it to change back to an object but it just doesn't seem to work.
Hopefully my dilemma is clear and someone knows a good way to do this in Javascript or Jquery.
Thanks in advance.
You don't need anything as complicated as you are making it. Just concatenate your strings.
var jsonp = "bio(" + json + ");"
I've gotten closest with Stringify
JSON is already a string. You only need to stringify something if you have a JavaScript data structure and want to convert it to JSON.
I'm sending a JSON object to ruby with javascript. But I cannot parse it in there. I tried following stuff but no luck. Also I've been searching around for while now, but I couldn't find anything helpful.
Note that I'm very new ruby.
My trials:
def initialize(game_conf_json)
parsed_conf = JSON.parse(conf_json)
#param1 = parsed_conf['name'][0]
#param2 = parsed_conf['surname'][0]
=begin
I also tried this:
#param1 = parsed_conf['name']
#param2 = parsed_conf['surname']
But no matter what other things I try, I'm getting the following error:
"21:in `[]': can't convert String into Integer (TypeError)"
OR
"can't convert Array into String (TypeError), "
=end
File.open("some_direc/conf.json", "w") do |f|
f.write(game_conf_json)
end
end
I create the json in javascript like this:
var json_of_form_vars = {};
json_of_form_vars.name = name_val;
json_of_form_vars.surname = surname_val;
And send it this way:
$.ajax({
url: "../fundament/dispatch.rb/",
type: "post",
dataType: "json",
data: "conf="+json_of_form_vars,
.....
How can I solve this problem? Is there any proper tutorial for this of problem?
UPDATE1 (After suggestions):
I used JSON.stringify and then passed the object to ruby. And then I finally able to print the object in ruby. It's listed below:
{"name": "METIN", "surname": "EMENULLAHI"}
The method .class claims that it is an array. But I cannot access data with classical ways, like:
array['name']
the error is:
can't convert String into Integer
And when I try to pass it to the JSON.parse in ruby, it gives me the following error:
can't convert Array into String
So I used JSON.parse(conf_array.to_json), but again when accessing the data it gives the same error like arrays:
can't convert String into Integer
What should be done now?
UPDATE2
Here is my cgi handler which passes the URL parameters to appropriate places:
cgi_req = CGI::new
puts cgi_req.header
params_from_request = cgi_req.params
logger.error "#{params_from_request}"
action_todo = params_from_request['action'][0].chomp
base = Base.new
if action_todo.eql?('create')
conf_json = params_from_request['conf']
# This line prints the json like this: {"name": "SOME_NAME", "surname": "SOME_SURNAME"}
logger.error "#{conf_json}"
base.create_ident(conf_json)
end
And in Base class:
def create_ident(conf_json)
require 'src/IdentityCreation'
iden_create = IdentityCreation.new(conf_json)
end
IdentityCreation's constructor is listed above.
UPDATE3:
Ok, I now get at least something out of the array. But when I access a key, it displays the key itself:
parsed_conf = JSON.parse(conf_json.to_json)
#param1 = parsed_conf[0]['name']
#param2 = parsed_conf[0]['surname']
# At this point when I print the #param1, it gives me "name"(the key), not "SOME_NAME"(the value).
Here an example of parsing a JSON string. If you still have problems, publish the generated JSON so that we can try it.
require 'json'
require 'ap'
string = %{
{"configurations" : [
{ "drinks" : [
{"menus" : [
{ "hot" : [
{"id":15,"unit":"0.33", "price":"1", "currency":"Euro", "position": 4},
{"id":15,"unit":"0.33", "price":"1", "currency":"Euro", "position": 6}
] },
{ "cold" : [
{"id":15,"unit":"0.33", "price":"1", "currency":"Euro", "position": 4},
{"id":15,"unit":"0.33", "price":"1", "currency":"Euro", "position": 6}
] },
{ "terminals" : { "id" : 4, "id": 6, "id": 7 } },
{ "keys" : { "debit" : "on", "credit": "off" } }
] }
] } ] }
}
hash = JSON.parse(string)
ap hash
gives
{
"configurations" => [
[0] {
"drinks" => [
[0] {
"menus" => [
[0] {
"hot" => [
[0] {
"id" => 15,
"unit" => "0.33",
"price" => "1",
"currency" => "Euro",
"position" => 4
},
etc..
At the moment you're not actually posting json. You're attemping to post json wrapped inside form encoded parameters. In addition, when you do
"conf=" + json_of_form_vars
javascript will convert json_of_form_vars to a string for you but that conversion isn't the same as dumping to JSON. Javascript default string conversions are pretty useless for objects, so you'll need to use JSON.stringify to get actual json.
Since you're composing the body as a string literal you'll also need to escape any special characters that aren't allowed (or have special meaning) in this context. It's usually easier to let jquery do the heavy lifting, with something like
$.ajax({
url: "../fundament/dispatch.rb/",
type: "post",
dataType: "json",
data: {conf: JSON.stringify(json_of_form_vars)}
I solved it finally. Using all the suggestions made under this post and also my irb experiences with hashes, arrays, json and etc.
So instead of converting my object (conf_json) to json (with to_json), I passed it to JSON.parse as a string like below:
parsed_conf = JSON.parse(%{#{conf_json}})
It seems kind of weird to me, because when try to pass it to function like below, I got the error of can't convert Array into String.
parsed_conf = JSON.parse(conf_json)
But it is working like a charm right now.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
JSON pretty print using JavaScript
I'm working on a project that will be used to help analyse and understand JSON arrays by future developers of a platform. I'm referencing Facebook's brilliant Graph Explorer page, seen here, and want to output our array in a prettified, correctly tab indented and line breaker array, just as it does on the explorer.
The arrays are outputted to a textarea, and because of this I think I'm running into issues with the line breaking and tabbing. I've also tried using the prettify library, but with no luck.
Example:
{"outcome" : "success", "result" : {"name" : "messaging-sockets", "default-interface" : "external", "include" : [], "socket-binding" : {"messaging" : {"name" : "messaging", "interface" : null, "port" : 5445, "fixed-port" : null, "multicast-address" : null, "multicast-port" : null}, "messaging-throughput" : {"name" : "messaging-throughput", "interface" : null, "port" : 5455, "fixed-port" : null, "multicast-address" : null, "multicast-port" : null}}}, "compensating-operation" : null}
To:
{
"outcome":"success",
"result":{
"name":"messaging-sockets",
"default-interface":"external",
"include":[
],
"socket-binding":{
"messaging":{
"name":"messaging",
"interface":null,
"port":5445,
"fixed-port":null,
"multicast-address":null,
"multicast-port":null
},
"messaging-throughput":{
"name":"messaging-throughput",
"interface":null,
"port":5455,
"fixed-port":null,
"multicast-address":null,
"multicast-port":null
}
}
},
"compensating-operation":null
}
You may use JSON.stringify:
JSON.stringify(jsonobj,null,'\t')
See the demo.
UPDATE: If you don't have jsonobj,but have json string,then before using stringify function,convert json string to json object by this line:
jsonobj = JSON.parse(jsonstring);