Jump to content
Korean Random
Sign in to follow this  
yan-polonov

Json - local / server data

Recommended Posts

Доброго времени суток, может кто нибудь привести простой пример по импорту параметров из внешнего json-файла (локального / серверного).

 

Сейчас юзаю обычные xml-ки

 

'local'

import ResMgr

localPrm = 'null'

xml = ResMgr.openSection('../res_mods/configs/data.xml')
if xml is not None:
    localPrm = xml.readString('localParametrs')
else:
    print '[ERROR] Unable to load local data file'

'server'

import urllib2
from xml.dom.minidom import parseString

serverPrm = 'null'

try:
    file = urllib2.urlopen('http://pastebin.com/raw/***')
    data = file.read()
    file.close()
    dom = parseString(data)
    serverPrm = dom.getElementsByTagName('serverParametrs')[0].firstChild.data
except:
    print '[ERROR] Unable to load server data file'

Edited by yan-polonov

Share this post


Link to post

Short link
Share on other sites

@yan-polonov,

import json
with open('file.json', 'r') as f:
    data = json.load(f)
Хотя я видел и такое:

with open('file.json', 'r') as f:
    exec 'data = ' + f.read()

xml.dom.minidom

Не юзайте это для чтения. В питоне есть прекрасный ElementTree Edited by ShadowHunterRUS
  • Upvote 1

Share this post


Link to post

Short link
Share on other sites
пример по импорту параметров из внешнего json-файла локального

 

'Файл на клиенте'

import json
cfg = {}

def config_load():
    try:
        global cfg
        file = open('res_mods/configs/***.json', 'r')
        f = file.read()
        while f.count('/*'):
            f = f.replace(f[f.find('/*'):f.find('*/') + 2 if f.find('*/') + 2 != 1 else len(f)], '')
        while f.count('//'):
            f = f.replace(f[f.find('//'):f.find('\n', f.find('//')) if f.find('\n', f.find('//')) != -1 else len(f)], '')
        cfg = json.loads(f)
    except IOError:
        print '[ERROR] Unable to load config file (local)'
    finally:
        file.close()

config_load()

Импорт содержимого из конфигурационного файла:

localData = cfg['localData']
print localData
{
  "localData": "Test text: localData"
}

 

пример по импорту параметров из внешнего json-файла серверного

 

'Файл на сервере'

import json
import urllib2

cfg = {}

def config_load():
    try:
        global cfg
        file = urllib2.urlopen('http://www.***.json')
        f = file.read()
        while f.count('/*'):
            f = f.replace(f[f.find('/*'):f.find('*/') + 2 if f.find('*/') + 2 != 1 else len(f)], '')
        while f.count('//'):
            f = f.replace(f[f.find('//'):f.find('\n', f.find('//')) if f.find('\n', f.find('//')) != -1 else len(f)], '')
        cfg = json.loads(f)
    except IOError:
        print '[ERROR] Unable to load config file (server)'
    finally:
        file.close()

config_load()

Импорт содержимого из конфигурационного файла:

serverData = cfg['serverData']
print serverData
{
  "serverData": "Test text: serverData"
}

Edited by night_dragon_on
  • Upvote 1

Share this post


Link to post

Short link
Share on other sites

Спасибо за помощь, взял пример из третьего поста - работает.

 

Update

 

А вот еще такой вопрос:

 

Попробовал вытянуть данные в таков виде:

{
  "enable": true,
  "data": "text_data ..."
}

Все норм, а вот если я хочу вывести текст в таком виде:

 

'Текст (в столбец с переносами)'

{
  "enable": true,
  "data_text": "
    * Сбор на форуме запланирован на 17.07.16 в 21:00 МСК
      - Бла Бла Бла
      - Бла Бла Бла
      - Бла Бла Бла"
}
  File "mod_clan_news", line 58, in <module>
  File "mod_clan_news", line 52, in configServer
  File "scripts/common/Lib/json/__init__.py", line 338, in loads
  File "scripts/common/Lib/json/decoder.py", line 366, in decode
  File "scripts/common/Lib/json/decoder.py", line 382, in raw_decode
ValueError: Invalid control character at: line 4 column 17 (char 82)

'Код'

#example from: http://www.koreanrandom.com/forum/topic/32698-

import json
import urllib2

cfg = {}

def configServer():
    try:
        global cfg
        file = urllib2.urlopen('http://pastebin.com/raw/***')
        f = file.read()
        while f.count('/*'):
            f = f.replace(f[f.find('/*'):f.find('*/') + 2 if f.find('*/') + 2 != 1 else len(f)], '')
        while f.count('//'):
            f = f.replace(f[f.find('//'):f.find('\n', f.find('//')) if f.find('\n', f.find('//')) != -1 else len(f)], '')
        cfg = json.loads(f)
    except IOError:
        print '[ERROR] Unable to load config file (server)'
    finally:
        file.close()

configServer()

data_text = cfg['data_text']

from gui.SystemMessages import pushMessage, SM_TYPE
msg = '<font color="#FEFEFE">Предстоящие события:</font><font color="#96FF00">\n' + data_text + '</font>'
pushMessage(msg, SM_TYPE.GameGreeting)

 

Как его правильно прописать?

Edited by yan-polonov

Share this post


Link to post

Short link
Share on other sites

Вариант 1:
"data_text": "* Сбор на форуме запланирован на 17.07.16 в 21:00 МСК\n- Бла Бла Бла\n- Бла Бла Бла\n- Бла Бла Бла"

Вариант2:
"data_text": [
"* Сбор на форуме запланирован на 17.07.16 в 21:00 МСК",
"- Бла Бла Бла",
"- Бла Бла Бла",
"- Бла Бла Бла"
]

А в питоне использовать ''.join для получения из data_text строки
  • Upvote 1

Share this post


Link to post

Short link
Share on other sites

А в питоне использовать ''.join для получения из data_text строки

 

Первый вариант не очень удобен, а вот второй как раз думаю.

data_text = ('\n'.join(cfg['data_text']))

Всем кто откликнулся большое человеческое спасибо, все таки на этом форуме пользователи с доброй душой

 

Не то что офф. форум давно уже именуемый как "Раковый"

 

Вопрос решен. Тему закрою.

Edited by yan-polonov

Share this post


Link to post

Short link
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Sign in to follow this  

  • Recently Browsing   0 members

    No registered users viewing this page.

×
×
  • Create New...